Ejemplo n.º 1
0
        /// <summary>
        /// Обновление даты начала исполнения и завершения задачи
        /// </summary>
        private void UpdateStartAndCompletionDates()
        {
            #region StartDate
            {
                var newList          = ExecutionHistory.Where(x => x.ExecutionState.ExecutionStateType == TaskExecutionStateType.New).Select(x => x.Date);
                var lastNewStateDate = DateTimeUtils.GetMaxDate(newList);

                var execList = ExecutionHistory.Where(x => x.ExecutionState.ExecutionStateType != TaskExecutionStateType.New).Select(x => x.Date);
                // Если статуса "новая" задача не имела, то берем все даты исполнений со статусом "в работе"
                var execStateDate = DateTimeUtils.GetMinDate(execList.Where(x => lastNewStateDate != null ? x > lastNewStateDate : true));

                if (StartDate != execStateDate)
                {
                    StartDate = execStateDate;  // выставляем новую дату начала исполнения
                }
            }
            #endregion

            #region ComletionDate
            {
                var openList          = ExecutionHistory.Where(x => x.ExecutionState.ExecutionStateType != TaskExecutionStateType.Completed).Select(x => x.Date);
                var lastOpenStateDate = DateTimeUtils.GetMaxDate(openList);

                var comletedList = ExecutionHistory.Where(x => x.ExecutionState.ExecutionStateType == TaskExecutionStateType.Completed).Select(x => x.Date);
                // Если "открытых" статусов задача не имела, то берем все даты исполнений с "закрытым" статусом
                var comletionStateDate = DateTimeUtils.GetMinDate(comletedList.Where(x => lastOpenStateDate != null ? x > lastOpenStateDate : true));

                if (FactualCompletionDate != comletionStateDate)
                {
                    FactualCompletionDate = comletionStateDate;
                }
            }
            #endregion
        }
Ejemplo n.º 2
0
        public void AuditCommandConsumer_Consume_ExecutionAuditCommand()
        {
            var resourceId       = Guid.NewGuid();
            var executionHistory = new ExecutionHistory
            {
                ResourceId = resourceId,
            };

            object parameters = new object();

            var auditCommand = new AuditCommand
            {
                Type             = "ExecutionAuditCommand",
                ExecutionHistory = executionHistory,
            };

            var mockLoggerConsumer = new Mock <ILoggerConsumer <IAuditEntry> >();

            mockLoggerConsumer.Setup(o => o.Consume(auditCommand.ExecutionHistory, parameters)).Verifiable();
            var mockSocket = new Mock <IWebSocketConnection>();
            var mockWriter = new Mock <IWriter>();

            mockWriter.Setup(o => o.WriteLine("Logging Server OnMessage: Type:" + auditCommand.Type)).Verifiable();
            mockWriter.Setup(o => o.WriteLine(auditCommand.ExecutionHistory.ResourceId.ToString())).Verifiable();

            var auditCommandConsumer = new AuditCommandConsumer(mockLoggerConsumer.Object, mockSocket.Object, mockWriter.Object);

            auditCommandConsumer.Consume(auditCommand, parameters);

            mockLoggerConsumer.Verify(o => o.Consume(auditCommand.ExecutionHistory, parameters), Times.Once);
            mockWriter.Verify(o => o.WriteLine("Logging Server OnMessage: Type:" + auditCommand.Type), Times.Once);
            mockWriter.Verify(o => o.WriteLine(auditCommand.ExecutionHistory.ResourceId.ToString()), Times.Once);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Обновить задачу по последнему исполнению
        /// </summary>
        protected internal virtual void UpdateByLastExecution()
        {
            var maxDate       = DateTimeUtils.GetMaxDate(ExecutionHistory.Select(x => x.Date));
            var lastExecution = ExecutionHistory.Where(x => x.Date == maxDate).First();

            UpdateTaskExecutionState(lastExecution);
            CompletionPercentage = lastExecution.CompletionPercentage;
            UpdateStartAndCompletionDates();
        }
Ejemplo n.º 4
0
        private void CreateExecutionError(Task <ConsumerResult> requestForwarderResult, Guid executionId, DateTime startDate, DateTime endDate, TimeSpan duration)
        {
            var executionInfo  = new ExecutionInfo(startDate, duration, endDate, Warewolf.Triggers.QueueRunStatus.Error, executionId);
            var executionEntry = new ExecutionHistory(_resourceId, "", executionInfo, _userName);

            executionEntry.Exception = requestForwarderResult.Exception;
            executionEntry.AuditType = "Error";
            _logger.ExecutionFailed(executionEntry);
        }
Ejemplo n.º 5
0
        private void LogExecutionCompleted(ExecutionHistory executionHistory)
        {
            var command = new AuditCommand
            {
                Type             = "ExecutionAuditCommand",
                ExecutionHistory = executionHistory
            };

            Publish(Serializer.Serialize(command));
        }
Ejemplo n.º 6
0
        public Task <ConsumerResult> Consume(byte[] body, object parameters)
        {
            var headers = parameters as Headers;

            if (!headers.KeyExists("Warewolf-Execution-Id"))
            {
                headers["Warewolf-Execution-Id"] = new[] { Guid.NewGuid().ToString() };
            }

            var    empty               = new string[] { };
            var    executionId         = Guid.Parse(headers["Warewolf-Execution-Id"].FirstOrDefault());
            var    customTransactionID = headers["Warewolf-Custom-Transaction-Id", empty].FirstOrDefault();
            string strBody             = System.Text.Encoding.UTF8.GetString(body);

            _logger.StartExecution($"[{executionId}] - {customTransactionID} processing body {strBody} ");
            var startDate = DateTime.UtcNow;

            Task <ConsumerResult> task = null;

            try
            {
                task = _consumer.Consume(body, parameters);
                task.Wait();

                var endDate  = DateTime.UtcNow;
                var duration = endDate - startDate;

                if (task.Result == ConsumerResult.Success)
                {
                    _logger.Info($"[{executionId}] - {customTransactionID} success processing body {strBody}");
                    var executionInfo = new ExecutionInfo(startDate, duration, endDate,
                                                          Warewolf.Triggers.QueueRunStatus.Success, executionId, customTransactionID);
                    var executionEntry = new ExecutionHistory(_resourceId, "", executionInfo, _userName);
                    _logger.ExecutionSucceeded(executionEntry);
                }
                else
                {
                    _logger.Error($"Failed to execute {_resourceId + " [" + executionId + "] " + strBody}");
                    CreateExecutionError(task, executionId, startDate, endDate, duration,
                                         customTransactionID);
                }

                return(Task.Run(() => ConsumerResult.Success));
            }
            catch (Exception)
            {
                var endDate  = DateTime.UtcNow;
                var duration = endDate - startDate;
                _logger.Warn($"[{executionId}] - {customTransactionID} failure processing body {strBody}");
                CreateExecutionError(task, executionId, startDate, endDate, duration,
                                     customTransactionID);

                return(Task.Run(() => ConsumerResult.Failed));
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Adds last instruction to the execution history
        /// </summary>
        /// <param name="in_instruction_start_pc">PC where the instruction begins</param>
        /// <param name="in_instruction_t_cycle">T cycle used for execution</param>
        private void AddInstructionToExecutionHistory(ushort in_instruction_start_pc, uint in_instruction_t_cycle)
        {
            ExecutionHistoryEntry history_entry = ExecutionHistory.GetNextEmptySlot();

            history_entry.PC     = in_instruction_start_pc;
            history_entry.TCycle = in_instruction_t_cycle;

            for (int i = 0; i < ExecutionHistoryEntry.HistoryEntryByteBufferLength; i++)
            {
                history_entry.Bytes[i] = TVC.Memory.Read((ushort)(in_instruction_start_pc + i));
            }
        }
Ejemplo n.º 8
0
        public Task <ConsumerResult> Consume(byte[] body)
        {
            var    executionId = Guid.NewGuid();
            string strBody     = System.Text.Encoding.UTF8.GetString(body);

            _logger.StartExecution($"processing body {strBody}");
            var startDate = DateTime.UtcNow;

            var task = _consumer.Consume(body);

            task.ContinueWith((requestForwarderResult) =>
            {
                var endDate  = DateTime.UtcNow;
                var duration = endDate - startDate;

                _logger.Warn($"failure processing body {strBody}");
                var executionInfo        = new ExecutionInfo(startDate, duration, endDate, Warewolf.Triggers.QueueRunStatus.Error, executionId);
                var executionEntry       = new ExecutionHistory(_resourceId, "", executionInfo, _userName);
                executionEntry.Exception = requestForwarderResult.Exception;

                _logger.ExecutionFailed(executionEntry);
            }, TaskContinuationOptions.OnlyOnFaulted);

            task.ContinueWith((requestForwarderResult) =>
            {
                var endDate  = DateTime.UtcNow;
                var duration = endDate - startDate;

                if (requestForwarderResult.Result == ConsumerResult.Success)
                {
                    _logger.Info($"success processing body{strBody}");
                    var executionInfo  = new ExecutionInfo(startDate, duration, endDate, Warewolf.Triggers.QueueRunStatus.Success, executionId);
                    var executionEntry = new ExecutionHistory(_resourceId, "", executionInfo, _userName);

                    _logger.ExecutionSucceeded(executionEntry);
                }
            }, TaskContinuationOptions.OnlyOnRanToCompletion);

            if (task.IsFaulted)
            {
                return(Task.Run(() => ConsumerResult.Failed));
            }
            else
            {
                return(Task.Run(() => ConsumerResult.Success));
            }
        }
Ejemplo n.º 9
0
        private void LoadExecutionHistoryintoElastic(Guid executionId, Guid resourceId, string auditType, string detail, string eventLevel)
        {
            var dependency   = new Depends(Depends.ContainerType.AnonymousElasticsearch);
            var hostName     = "http://" + dependency.Container.IP;
            var port         = dependency.Container.Port;
            var loggerSource = new SerilogElasticsearchSource
            {
                Port        = port,
                HostName    = hostName,
                SearchIndex = "warewolftestlogs"
            };
            var uri    = new Uri(hostName + ":" + port);
            var logger = new LoggerConfiguration()
                         .MinimumLevel.Verbose()
                         .WriteTo.Sink(new ElasticsearchSink(new ElasticsearchSinkOptions(uri)
            {
                AutoRegisterTemplate = true,
                IndexDecider         = (e, o) => loggerSource.SearchIndex,
            }))
                         .CreateLogger();

            var mockSeriLogConfig = new Mock <ISeriLogConfig>();

            mockSeriLogConfig.SetupGet(o => o.Logger).Returns(logger);

            using (var loggerConnection = loggerSource.NewConnection(mockSeriLogConfig.Object))
            {
                var loggerPublisher  = loggerConnection.NewPublisher();
                var executionInfo    = new ExecutionInfo(DateTime.Now, DateTime.Now - DateTime.UtcNow, DateTime.Today, Triggers.QueueRunStatus.Success, executionId, executionId.ToString());
                var executionHistory = new ExecutionHistory(resourceId, "", executionInfo, "username");
                //-------------------------Act----------------------------------
                if (eventLevel == "Debug")
                {
                    loggerPublisher.Debug(GlobalConstants.WarewolfLogsTemplate, executionHistory);
                }
                else
                {
                    loggerPublisher.Info(GlobalConstants.WarewolfLogsTemplate, executionHistory);
                }
            }

            Task.Delay(225).Wait();
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Generates debug event (refreshes debug information display)
        /// </summary>
        private void GenerateDebugEvent(bool in_force_event)
        {
            // generate debug event
            if (m_thread_running)
            {
                DateTime current_time = DateTime.Now;

                if (in_force_event || (current_time - m_debug_event_timestamp).TotalMilliseconds > DebugEventPeriod)
                {
                    m_debug_event_timestamp = current_time;

                    ExecutionHistory.UpdateHistory();

                    m_context.Post(delegate
                    {
                        DebuggerBreakEvent?.Invoke(TVC);
                    }, null);
                }
            }
        }
Ejemplo n.º 11
0
 public void SetUp()
 {
     @class = new Class(typeof(TestService));
     executionHistory = new ExecutionHistory();
     serviceExecution = new ServiceExecution(executionHistory, new NullWorkEnvironment());
 }
Ejemplo n.º 12
0
 public void SetUp()
 {
     @class           = new Class(typeof(TestService));
     executionHistory = new ExecutionHistory();
     serviceExecution = new ServiceExecution(executionHistory, new NullWorkEnvironment());
 }
Ejemplo n.º 13
0
 public void ExecutionSucceeded(ExecutionHistory executionHistory)
 {
     LogExecutionCompleted(executionHistory);
 }
Ejemplo n.º 14
0
 public void ExecutionFailed(ExecutionHistory executionHistory)
 {
     LogExecutionCompleted(executionHistory);
 }
 public void Setup()
 {
     type             = typeof(TestService);
     executionHistory = new ExecutionHistory();
     serviceExecution = new ServiceExecution(executionHistory, new NullWorkEnvironment());
 }
Ejemplo n.º 16
0
        /// <summary>
        /// Определение, является ли исполнение последним
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        private bool IsLastExecution(TaskExecutionItem item)
        {
            var maxDate = DateTimeUtils.GetMaxDate(ExecutionHistory.Select(x => x.Date));

            return(item.Date == maxDate);
        }