Example #1
0
        /// <summary>
        ///     Handles the specified event to handle.
        /// </summary>
        /// <param name="eventToHandle">The event to handle.</param>
        public void Handle([NotNull] Event eventToHandle)
        {
            var data = eventToHandle.Data;

            if ((data == null) || !data.ContainsKey(Variables.TaskId))
            {
                return;
            }

            var taskId = long.Parse(data[Variables.TaskId]);
            var task   = _taskRepository.GetById(taskId);

            if (task.TaskResolutionStatus == TaskResolutionStatus.Error)
            {
                _eventProvider.Publish(
                    new Event
                {
                    Key  = EventKeys.ScanTask.Failed,
                    Data = new Dictionary <string, string>
                    {
                        { Variables.ProjectId, task.ProjectId.ToString() },
                        { Variables.TaskId, task.Id.ToString() }
                    }
                });
            }

            if (task.TaskResolutionStatus == TaskResolutionStatus.Cancelled)
            {
                _eventProvider.Publish(
                    new Event
                {
                    Key  = EventKeys.ScanTask.Cancelled,
                    Data = new Dictionary <string, string>
                    {
                        { Variables.ProjectId, task.ProjectId.ToString() },
                        { Variables.TaskId, task.Id.ToString() }
                    }
                });
            }

            if (task.Projects.DefaultBranchName != task.Repository)
            {
                return;
            }

            _eventProvider.Publish(
                new Event
            {
                Key  = EventKeys.Policy.CheckRequired,
                Data = new Dictionary <string, string>
                {
                    { Variables.ProjectId, task.ProjectId.ToString() },
                    { Variables.TaskId, task.Id.ToString() }
                }
            });
        }
 private void PublishPolicyEvent(Event eventToHandle, string key) =>
 _eventProvider.Publish(
     new Event
 {
     Key  = key,
     Data = eventToHandle.Data
 });
Example #3
0
        public void ShouldSendSerializedEventToQueueWriter()
        {
            _target.Publish(_event);

            _messageQueue.Verify(_ => _.BeginWrite(MessageQueueKeys.Events), Times.Once);
            _queueWriter.Verify(_ => _.Send(SerializedEvent), Times.Once);
            _queueWriter.Verify(_ => _.Dispose(), Times.Once);
        }
 private void SendEvent(long projectId, string branchName) =>
 _eventProvider.Publish(
     new Event
 {
     Key  = EventKeys.VcsCommitted,
     Data = new Dictionary <string, string>
     {
         { Variables.ProjectId, projectId.ToString() },
         { Variables.Branch, branchName }
     }
 });
 /// <summary>
 ///     Publishes the task event.
 /// </summary>
 /// <param name="eventName">Name of the event.</param>
 /// <param name="taskId">The task identifier.</param>
 /// <param name="projectId">The project identifier.</param>
 protected void PublishTaskEvent(string eventName, long taskId, long projectId) =>
 _eventProvider.Publish(
     new Event
 {
     Key  = eventName,
     Data = new Dictionary <string, string>
     {
         { Variables.TaskId, taskId.ToString() },
         { Variables.ProjectId, projectId.ToString() }
     }
 });
        public void Handle(Event eventToHandle)
        {
            using (var telemetryScope = _telemetryScopeProvider.Create <Tasks>(TelemetryOperationNames.Task.Create))
            {
                try
                {
                    var projectId = long.Parse(eventToHandle.Data[Variables.ProjectId]);

                    var task = new Tasks
                    {
                        Created      = _timeService.GetUtc(),
                        CreatedById  = _userPrincipal.Info.Id,
                        Finished     = null,
                        Modified     = _timeService.GetUtc(),
                        ModifiedById = _userPrincipal.Info.Id,
                        ProjectId    = projectId,
                        Repository   = eventToHandle.Data[Variables.Branch],
                        SdlStatus    = (int)SdlPolicyStatus.Unknown
                    };

                    telemetryScope.SetEntity(task);

                    _taskRepository.Insert(task);

                    // TODO добавить копирования настроек с проекта
                    _eventProvider.Publish(
                        new Event
                    {
                        Key  = EventKeys.ScanTask.Created,
                        Data = new Dictionary <string, string>
                        {
                            { Variables.ProjectId, projectId.ToString() },
                            { Variables.TaskId, task.Id.ToString() }
                        }
                    });

                    telemetryScope.WriteSuccess();

                    _taskRepository.Save();

                    _log.Debug(Resources.TaskCreated.FormatWith(task.Id, projectId, task.Repository));
                }
                catch (Exception ex)
                {
                    telemetryScope.WriteException(ex);

                    throw;
                }
            }
        }
        protected override void ProcessAuthorized(CreateTaskCommand command)
        {
            using (var telemetryScope = _telemetryScopeProvider.Create <Tasks>(TelemetryOperationNames.Task.Create))
            {
                try
                {
                    var currentDateTime = _timeService.GetUtc();

                    var task = new Tasks
                    {
                        Created      = currentDateTime,
                        CreatedById  = _userPrincipal.Info.Id,
                        Finished     = null,
                        Modified     = currentDateTime,
                        ModifiedById = _userPrincipal.Info.Id,
                        ProjectId    = command.ProjectId,
                        Repository   = command.Repository,
                        SdlStatus    = (int)SdlPolicyStatus.Unknown
                    };

                    telemetryScope.SetEntity(task);

                    _repositoryTasks.Insert(task);

                    command.CreatedTaskId = task.Id;

                    _eventProvider.Publish(
                        new Event
                    {
                        Key  = EventKeys.ScanTask.Created,
                        Data = new Dictionary <string, string>
                        {
                            { Variables.ProjectId, command.ProjectId.ToString() },
                            { Variables.TaskId, task.Id.ToString() }
                        }
                    });

                    _repositoryTasks.Save();

                    telemetryScope.WriteSuccess();
                }
                catch (Exception ex)
                {
                    telemetryScope.WriteException(ex);

                    throw;
                }
            }
        }
        /// <summary>
        ///     Handles the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>The result of request execution.</returns>
        public ApiResponse Handle([NotNull] ApiRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            if (string.IsNullOrWhiteSpace(request.SourceType))
            {
                throw new ArgumentException(Resources.ApiService_Handle_SourceTypeNotSpecified);
            }

            if (string.IsNullOrWhiteSpace(request.RequestMethod))
            {
                throw new ArgumentException(Resources.ApiService_Handle_RequestMethodNotSpecified);
            }

            var executor = _requestExecutorProvider.Get(request.SourceType);

            if (!executor.CanHandleAsync(request))
            {
                return(executor.Execute(request));
            }

            _eventProvider.Publish(
                new Event
            {
                Key  = EventKeys.ExternalSystemAction,
                Data = new Dictionary <string, string>
                {
                    {
                        "Data", JsonConvert.SerializeObject(request)
                    }
                }
            });

            _unitOfWork.Commit();

            return(new ApiResponse
            {
                Success = true
            });
        }
        protected override void ProcessAuthorized(StopTaskCommand command)
        {
            using (var telemetryScope = _telemetryScopeProvider.Create <Tasks>(TelemetryOperationNames.Task.Stop))
            {
                try
                {
                    var task = _repositoryTasks.GetById(command.TaskId);

                    telemetryScope.SetEntity(task);

                    task.Modified        = _timeService.GetUtc();
                    task.ModifiedById    = _userPrincipal.Info.Id;
                    task.SdlPolicyStatus = SdlPolicyStatus.Unknown;

                    task.Cancel();

                    _eventProvider.Publish(
                        new Event
                    {
                        Key  = EventKeys.ScanTask.Finished,
                        Data = new Dictionary <string, string>
                        {
                            { Variables.TaskId, task.Id.ToString() },
                            { Variables.ProjectId, task.ProjectId.ToString() }
                        }
                    });

                    _repositoryTasks.Save();

                    telemetryScope.WriteSuccess();
                }
                catch (Exception ex)
                {
                    telemetryScope.WriteException(ex);

                    throw;
                }
            }
        }
        /// <summary>
        ///     Gets the next task.
        /// </summary>
        /// <param name="info">The information.</param>
        /// <returns></returns>
        private ScanTaskDto GetNextTask([NotNull] GetScanTaskDto info)
        {
            if (info == null)
            {
                throw new ArgumentNullException(nameof(info));
            }

            var task = _taskRepository
                       .GetByStatus(TaskStatus.ReadyToScan)
                       .OrderBy(x => x.Created)
                       .FirstOrDefault();

            if (task == null)
            {
                return(null);
            }

            long scanAgentId;

            try
            {
                scanAgentId = _scanAgentRepository.GetByUid(info.ScanAgentId).Id;
            }
            catch (Exception exc)
            {
                throw new Exception($"Incorrect scan agent identifier. ScanAgentId='{info.ScanAgentId}'", exc);
            }

            task.StartScanning(scanAgentId);

            _eventProvider.Publish(
                new Event
            {
                Key  = EventKeys.ScanTask.ScanningStarted,
                Data = new Dictionary <string, string>
                {
                    {
                        Variables.ProjectId, task.ProjectId.ToString()
                    },
                    {
                        Variables.TaskId, task.Id.ToString()
                    },
                    {
                        Variables.ScanAgentId, info.ScanAgentId
                    }
                }
            });

            _taskRepository.Save();

            var settings =
                _settingValuesRepository
                .Query()
                .Where(
                    _ => (_.EntityId == task.ProjectId) &&
                    (_.Settings.SettingOwner == (int)SettingOwner.Project) &&
                    !_.Settings.IsArchived)
                .ToArray();

            var coreKeys = new Dictionary <string, string>
            {
                {
                    "sharp", "sharp"
                },
                {
                    "java", "java"
                },
                {
                    "php", "php"
                },
                {
                    "pm", "pattern_matching"
                },
                {
                    "fingerprint", "fingerprint"
                },
                {
                    "config", "configurations"
                },
                {
                    "blackbox", "blackbox"
                }
            };

            var activeCores = coreKeys.Where(
                coreKey =>
            {
                var setting = settings.FirstOrDefault(_ => _.Settings.Code == coreKey.Key + "-use");
                if (setting == null)
                {
                    return(false);
                }

                var value = Convert.ToBoolean(setting.Value);
                return(value);
            }).ToArray();

            var taskParameters = new Dictionary <string, string>
            {
                { "FolderPath", task.FolderPath }
            };

            var cores = activeCores.Select(
                _ =>
            {
                var coreSettings = settings
                                   .Where(coreSetting => coreSetting.Settings.Code.StartsWith(_.Key + "-", StringComparison.Ordinal)).ToArray();

                var parameters = coreSettings.Select(
                    coreSetting =>
                    _parameterTranslatorProvider.Get(
                        coreSetting.Settings.Code.Replace(_.Key + "-", string.Empty),
                        taskParameters)?
                    .Translate(coreSetting.Value))
                                 .Where(value => !string.IsNullOrWhiteSpace(value))
                                 .ToSeparatedString(" ");

                var path         = task.FolderPath;
                var codeLocation =
                    coreSettings.FirstOrDefault(cs => cs.Settings.Code.Replace(_.Key + "-", string.Empty) == "code-location");
                if (!string.IsNullOrWhiteSpace(codeLocation?.Value))
                {
                    path = Path.Combine(path, codeLocation.Value);
                }

                return(new ScanTaskCoreDto
                {
                    Core = _.Value,
                    CodeLocation = path,
                    CoreParameters = parameters
                });
            }).ToArray();

            return(new ScanTaskDto
            {
                Id = task.Id,
                Path = task.FolderPath,
                Cores = cores
            });
        }