public IActionResult SendNotification([FromBody] BodyEventMessageBody message)
        {
            if (message == null)
            {
                return(Problem("POST body JSON object is null!"));
            }

            var settings = new JsonSerializerSettings
            {
                ContractResolver = new DefaultContractResolver
                {
                    NamingStrategy = new CamelCaseNamingStrategy()
                },
                Formatting        = Formatting.Indented,
                NullValueHandling = NullValueHandling.Ignore
            };

            object state = null;
            bool   parse = Enum.TryParse(typeof(PreingestActionStates), message.State, out state);

            if (!parse)
            {
                return(Problem("Parsing state failed!"));
            }

            //trigger full events
            _eventHub.Clients.All.SendAsync(nameof(IEventHub.SendNoticeEventToClient),
                                            JsonConvert.SerializeObject(new EventHubMessage
            {
                EventDateTime = message.EventDateTime,
                SessionId     = message.SessionId,
                Name          = message.Name,
                State         = (PreingestActionStates)state,
                Message       = message.Message,
                Summary       = message.HasSummary ? new PreingestStatisticsSummary {
                    Accepted = message.Accepted, Processed = message.Processed, Rejected = message.Rejected, Start = message.Start.Value, End = message.End.Value
                } : null
            }, settings)).GetAwaiter().GetResult();

            if ((PreingestActionStates)state == PreingestActionStates.Started || (PreingestActionStates)state == PreingestActionStates.Failed || (PreingestActionStates)state == PreingestActionStates.Completed)
            {
                //notify client update collections status
                string collectionsData = JsonConvert.SerializeObject(_preingestCollection.GetCollections(), settings);
                _eventHub.Clients.All.SendAsync(nameof(IEventHub.CollectionsStatus), collectionsData).GetAwaiter().GetResult();
                //notify client collection /{ guid} status
                string collectionData = JsonConvert.SerializeObject(_preingestCollection.GetCollection(message.SessionId), settings);
                _eventHub.Clients.All.SendAsync(nameof(IEventHub.CollectionStatus), message.SessionId, collectionData).GetAwaiter().GetResult();

                if ((PreingestActionStates)state == PreingestActionStates.Failed || (PreingestActionStates)state == PreingestActionStates.Completed)
                {
                    _eventHub.Clients.All.SendAsync(nameof(IEventHub.SendNoticeToWorkerService), message.SessionId, collectionData).GetAwaiter().GetResult();
                }
            }
            return(Ok());
        }
        public IActionResult GetCollection(Guid guid)
        {
            var directory = new DirectoryInfo(_settings.DataFolderName);

            if (!directory.Exists)
            {
                return(Problem(String.Format("Data folder '{0}' not found!", _settings.DataFolderName)));
            }

            if (guid == Guid.Empty)
            {
                return(Problem("Empty GUID is invalid."));
            }

            dynamic dataResults = null;

            try
            {
                dataResults = _preingestHandler.GetCollection(guid);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "An exception was thrown : {0}, '{1}'.", e.Message, e.StackTrace);
                return(ValidationProblem(String.Format("An exception was thrown : {0}, '{1}'.", e.Message, e.StackTrace)));
            }
            finally
            {
                _logger.LogInformation("Exit UpdateProcessAction.");
            }

            if (dataResults == null)
            {
                return(NotFound(String.Format("Not data found for collection '{0}'!", guid)));
            }

            return(new JsonResult(dataResults));
        }
示例#3
0
        public IActionResult StartPlan(Guid guid, [FromBody] BodyExecutionPlan workflow)
        {
            if (guid == Guid.Empty)
            {
                return(Problem("Empty GUID is invalid."));
            }

            if (workflow == null || workflow.Workflow.Length == 0)
            {
                return(Problem("No plan to run."));
            }

            _logger.LogInformation("Enter StartPlan.");
            try
            {
                var existingPlan   = new List <BodyPlan>();
                var currentArchive = _preingestCollection.GetCollection(guid);

                existingPlan = (currentArchive.ScheduledPlan as ExecutionPlanState[]) == null ? existingPlan : (currentArchive.ScheduledPlan as ExecutionPlanState[]).Select(item => new BodyPlan
                {
                    ActionName       = ((ValidationActionType)Enum.Parse(typeof(ValidationActionType), item.ActionName)),
                    ContinueOnError  = item.ContinueOnError,
                    ContinueOnFailed = item.ContinueOnFailed,
                    StartOnError     = item.StartOnError
                }).ToList();

                // the same action then remove old onces first
                // var exceptCollection = workflow.Workflow.Except<BodyPlan>(existingPlan).ToList();

                QueryResultAction[]      actions = currentArchive.Preingest as QueryResultAction[];
                List <QueryResultAction> alreadyProcessedActions = new List <QueryResultAction>();
                if (existingPlan.Count > 0)
                {
                    var intersectCollection = workflow.Workflow.Intersect <BodyPlan>(existingPlan).ToList();
                    var tempResult          = actions.Where(action
                                                            => intersectCollection.Exists(item
                                                                                          => item.ActionName == ((ValidationActionType)Enum.Parse(typeof(ValidationActionType), action.Name)))).ToList();

                    alreadyProcessedActions.AddRange(tempResult);
                }
                else
                {
                    var tempResult = actions.Where(action
                                                   => workflow.Workflow.ToList().Exists(item
                                                                                        => item.ActionName == ((ValidationActionType)Enum.Parse(typeof(ValidationActionType), action.Name)))).ToList();

                    alreadyProcessedActions.AddRange(tempResult);
                }
                //clean the old plan
                //remove previous states if selected in new plan
                //save the new plan
                using (var context = new PreIngestStatusContext())
                {
                    try
                    {
                        //get old plan, remove old plan, save
                        var oldPlan = context.ExecutionPlanCollection.Where(item => item.SessionId == guid).ToArray();
                        if (oldPlan.Length > 0)
                        {
                            context.ExecutionPlanCollection.RemoveRange(oldPlan);
                            context.SaveChanges();
                        }
                    }
                    catch (Exception e)
                    {
                        throw new ApplicationException("Failed to remove old plan! " + e.Message);
                    }
                    finally
                    {
                        try
                        {
                            //remove the old action + results + messages if found
                            if (alreadyProcessedActions.Count > 0)
                            {
                                var allStatusIdFromAlreadyProcessedActions = alreadyProcessedActions.SelectMany(item => item.States).Select(item => item.StatusId).ToArray();
                                var allActionIdFromAlreadyProcessedActions = alreadyProcessedActions.Select(item => item.ProcessId).ToArray();
                                //remove any error message
                                var messages = context.ActionStateMessageCollection.Where(item => allStatusIdFromAlreadyProcessedActions.Contains(item.StatusId)).ToArray();
                                context.ActionStateMessageCollection.RemoveRange(messages);
                                //remove any states
                                var states = context.ActionStateCollection.Where(item => allStatusIdFromAlreadyProcessedActions.Contains(item.StatusId)).ToArray();
                                context.ActionStateCollection.RemoveRange(states);
                                //remove any actions
                                var oldActions = context.PreingestActionCollection.Where(item => allActionIdFromAlreadyProcessedActions.Contains(item.ProcessId)).ToArray();
                                context.PreingestActionCollection.RemoveRange(oldActions);

                                context.SaveChanges();
                            }
                        }
                        catch (Exception e)
                        {
                            throw new ApplicationException("Failed to remove old action(s) + result(s) + message(s)! " + e.Message);
                        }
                        finally
                        {
                            try
                            {
                                //save the new plan
                                var newPlan = workflow.Workflow.Select((item, index) => new Entities.Context.ExecutionPlan {
                                    ActionName = item.ActionName.ToString(), SessionId = guid, ContinueOnError = item.ContinueOnError, ContinueOnFailed = item.ContinueOnFailed, StartOnError = item.StartOnError, Sequence = index
                                });
                                if (newPlan.Count() > 0)
                                {
                                    context.ExecutionPlanCollection.AddRange(newPlan);
                                    context.SaveChanges();
                                }
                            }
                            catch (Exception e)
                            {
                                throw new ApplicationException("Failed to save the new plan! " + e.Message);
                            }
                        }
                    }
                }

                var settings = new JsonSerializerSettings {
                    ContractResolver = new DefaultContractResolver {
                        NamingStrategy = new CamelCaseNamingStrategy()
                    }, Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Ignore
                };

                //reload
                currentArchive = _preingestCollection.GetCollection(guid);

                string collectionData = JsonConvert.SerializeObject(currentArchive, settings);
                _eventHub.Clients.All.SendAsync(nameof(IEventHub.SendNoticeToWorkerService), guid, collectionData).GetAwaiter().GetResult();
            }
            catch (Exception e)
            {
                _logger.LogInformation("Exit StartPlan.");
                return(ValidationProblem(e.Message));
            }

            _logger.LogInformation("Exit StartPlan.");
            return(Ok());
        }