示例#1
0
 private void OnDeploymentTaskStarting(DeploymentTask deploymentTask, DeploymentContext deploymentContext)
 {
     foreach (IDeploymentPipelineModule deploymentPipelineModule in _modules)
       {
     deploymentPipelineModule.OnDeploymentTaskStarting(deploymentTask, deploymentContext);
       }
 }
 private void OnDeploymentTaskFinished(DeploymentInfo deploymentInfo, DeploymentTask deploymentTask, DeploymentContext deploymentContext)
 {
     foreach (IDeploymentPipelineModule deploymentPipelineModule in _modules)
     {
         deploymentPipelineModule.OnDeploymentTaskFinished(deploymentInfo, deploymentTask, deploymentContext);
     }
 }
        private static string GetMainLogFilePath(DeploymentTask deploymentTask, DirectoryInfo deploymentJobsDirectory)
        {
            string contentFilePath = Path.Combine(deploymentJobsDirectory.FullName,
                                                  $"{deploymentTask.DeploymentTaskId}.txt");

            return(contentFilePath);
        }
示例#4
0
        protected override void DoPrepare()
        {
            List <ProjectInfo> dependentProjectsToDeploy = _projectInfoRepository.CreateDependentProjects(_projectName);

            if (!dependentProjectsToDeploy.Any())
            {
                PostDiagnosticMessage(string.Format("No dependent projects to deploy for project: [{0}]", _projectName), DiagnosticMessageType.Trace);
                return;
            }

            List <ProjectDeployment> defaultProjectDeployments = BuildDefaultProjectDeployments(dependentProjectsToDeploy, DefaultTeamCityProjectConfiguration);

            IEnumerable <ProjectDeployment> configuredProjectDeployments = ConfigureDeploymentsByClient(defaultProjectDeployments);

            foreach (ProjectDeployment projectDeployment in configuredProjectDeployments)
            {
                DeploymentTask deploymentTask = projectDeployment.ProjectInfo.CreateDeploymentTask(_objectFactory);

                try
                {
                    deploymentTask.Initialize(projectDeployment.DeploymentInfo);
                    deploymentTask.Prepare();

                    AddSubTask(deploymentTask);
                }
                catch (Exception exc)
                {
                    PostDiagnosticMessage(
                        string.Format("Error while preparing task: [{0}] with description: [{1}], exception: [{2}]", deploymentTask.GetType().FullName, deploymentTask.Description, exc),
                        DiagnosticMessageType.Error);
                }
            }
        }
示例#5
0
        private bool PrepareProject(ProjectDeploymentData projectDeploymentData, DeploymentContext deploymentContext)
        {
            DeploymentInfo deploymentInfo = projectDeploymentData.DeploymentInfo;
            DeploymentTask deploymentTask = projectDeploymentData.DeploymentTask;

            PostDiagnosticMessage(string.Format("Preparing {0} '{1}'.", (deploymentInfo.IsSimulation ? " (simulation)" : ""), deploymentTask.GetType().Name), DiagnosticMessageType.Info);

            deploymentTask.DiagnosticMessagePosted += OnDeploymentTaskDiagnosticMessagePosted;

            OnDeploymentTaskStarting(deploymentInfo, deploymentTask, deploymentContext);

            try
            {
                deploymentTask.Initialize(deploymentInfo);

                deploymentTask.Prepare();

                return(true);
            }
            catch (Exception exc)
            {
                PostDiagnosticMessage(string.Format("Exception while preparing: {0}", exc.Message), DiagnosticMessageType.Error);
            }
            finally
            {
                deploymentTask.DiagnosticMessagePosted -= OnDeploymentTaskDiagnosticMessagePosted;
            }

            return(false);
        }
示例#6
0
        protected override void ExecuteTask()
        {
            try
            {
                IProjectInfoRepository projectInfoRepository = ObjectFactory.Instance.CreateProjectInfoRepository();
                ProjectInfo            projectInfo           = projectInfoRepository.FindByName(ProjectName);
                DeploymentTask         deploymentTask        = projectInfo.CreateDeploymentTask(ObjectFactory.Instance);

                IDeploymentPipeline deploymentPipeline =
                    ObjectFactory.Instance.CreateDeploymentPipeline();

                deploymentPipeline.DiagnosticMessagePosted +=
                    (eventSender, tmpArgs) => Log(Level.Info, tmpArgs.Message);

                var deploymentContext = new DeploymentContext(RequesterIdentity);

                Guid deploymentId = Guid.NewGuid();

                var deploymentInfo =
                    new DeploymentInfo(
                        deploymentId,
                        IsSimulation,
                        ProjectName,
                        ConfigurationName,
                        BuildId,
                        Environment,
                        projectInfo.CreateEmptyInputParams());

                deploymentPipeline.StartDeployment(deploymentInfo, deploymentTask, deploymentContext);
            }
            catch (Exception exc)
            {
                Log(Level.Error, "Error: " + exc);
            }
        }
示例#7
0
        public void StartDeployment(DeploymentTask deploymentTask, DeploymentContext deploymentContext)
        {
            if (deploymentTask == null)
              {
            throw new ArgumentNullException("deploymentTask");
              }

              if (deploymentContext == null)
              {
            throw new ArgumentNullException("deploymentContext");
              }

              deploymentContext.DateStarted = DateTime.UtcNow;

              bool finishedSuccessfully = false;

              OnDeploymentTaskStarting(deploymentTask, deploymentContext);

              try
              {
            deploymentTask.PrepareAndExecute();

            finishedSuccessfully = true;
              }
              finally
              {
            deploymentContext.DateFinished = DateTime.UtcNow;
            deploymentContext.FinishedSuccessfully = finishedSuccessfully;

            // TODO IMM HI: catch exceptions; pass them upstream using some mechanisms like DeploymentTask.DiagnosticMessagePosted event
            OnDeploymentTaskFinished(
              deploymentTask,
              deploymentContext);
              }
        }
示例#8
0
        public void DeploymentProcessor_sequence_fail_task_details()
        {
            _task = TestTaskBuilder.SequenceTaskFail(_mediator);


            Assert(e => e.Result.Details.Contains(_task.Name) && e.Result.Details.Contains("failed"));
        }
        private static string LogJobMetadata(
            DeploymentTask deploymentTask,
            DateTime start,
            DateTime end,
            Stopwatch stopwatch,
            ExitCode exitCode,
            DirectoryInfo deploymentJobsDirectory,
            DeploymentTarget deploymentTarget)
        {
            var metadata = new StringBuilder();

            metadata
            .Append("Started job ")
            .Append(deploymentTask.DeploymentTaskId)
            .Append(" at ")
            .AppendFormat("{0:O}", start)
            .Append(" and finished at ")
            .AppendFormat("{0:O}", end).AppendLine();

            metadata
            .Append("Total time ")
            .AppendFormat("{0:f}", stopwatch.Elapsed.TotalSeconds)
            .AppendLine(" seconds");

            metadata
            .Append("Package version: ")
            .Append(deploymentTask.SemanticVersion)
            .AppendLine();

            metadata
            .Append("Package id: ")
            .AppendLine(deploymentTask.PackageId);

            metadata
            .Append("Target id: ")
            .AppendLine(deploymentTask.DeploymentTargetId);

            if (deploymentTarget is null)
            {
                metadata.AppendLine("Deployment target not found");
            }
            else
            {
                metadata.Append("Publish settings file: ").AppendLine(deploymentTarget.PublishSettingFile);
                metadata.Append("Target directory: ").AppendLine(deploymentTarget.TargetDirectory);
                metadata.Append("Target URI: ").Append(deploymentTarget.Url).AppendLine();
            }

            metadata.Append("Exit code ").Append(exitCode).AppendLine();

            string metadataContent = metadata.ToString();

            string metadataFilePath = Path.Combine(deploymentJobsDirectory.FullName,
                                                   $"{deploymentTask.DeploymentTaskId}.metadata.txt");

            File.WriteAllText(metadataFilePath, metadataContent, Encoding.UTF8);

            return(metadataContent);
        }
示例#10
0
        public static DeploymentTask SequenceTaskFail(IPublisher publisher)
        {
            var context = CreateContext("TaskFail", publisher);
            var task    = new DeploymentTask(context);

            task.Add(new FakeOpFail());
            return(task);
        }
 public void OnDeploymentTaskStarting(DeploymentTask deploymentTask, DeploymentContext deploymentContext)
 {
     if (deploymentTask.TargetEnvironmentName == ProductionEnvironmentName
        && deploymentTask.ProjectConfigurationName != ProductionProjectConfigurationName)
       {
     throw new InvalidOperationException(string.Format("Can't deploy project ('{0}') with non-production configuration ('{1}') to the production environment!", deploymentTask.ProjectName, deploymentTask.ProjectConfigurationName));
       }
 }
示例#12
0
        public static DeploymentTask SequenceTaskSuccess(IMediator mediator)
        {
            var context = CreateContext("TaskSuccess", mediator);
            var task    = new DeploymentTask(context);

            task.Add(new FakeOpSuccess());
            return(task);
        }
示例#13
0
        private void DoDeploy(Guid uniqueClientId, string requesterIdentity, Core.Domain.DeploymentInfo deploymentInfo, ProjectInfo projectInfo)
        {
            DeploymentTask deploymentTask = projectInfo.CreateDeploymentTask(ObjectFactory.Instance);

            Core.Domain.DeploymentInfo deployInfo = OverwriteConfigurationIfSelfDeployment(deploymentInfo, projectInfo);

            StartTask(deploymentTask, uniqueClientId, requesterIdentity, deployInfo);
        }
        private async Task <(ExitCode, DateTime)> RunDeploymentToolAsync(
            DeploymentTask deploymentTask,
            DirectoryInfo deploymentJobsDirectory,
            DeploymentTarget deploymentTarget,
            ILogger logger,
            CancellationToken cancellationToken = default)
        {
            string contentFilePath = GetMainLogFilePath(deploymentTask,
                                                        deploymentJobsDirectory);

            ExitCode exitCode;

            var logBuilder = new StringBuilder();

            LoggerConfiguration loggerConfiguration = new LoggerConfiguration()
                                                      .WriteTo.File(contentFilePath)
                                                      .WriteTo.DelegateSink(deploymentTask.Log)
                                                      .WriteTo.DelegateSink(message => logBuilder.AppendLine(message))
                                                      .WriteTo.Logger(logger);

            if (Debugger.IsAttached)
            {
                loggerConfiguration = loggerConfiguration.WriteTo.Debug(LogEventLevel.Verbose);
            }

            loggerConfiguration = loggerConfiguration.MinimumLevel.ControlledBy(_loggingLevelSwitch);

            using (Logger log = loggerConfiguration.CreateLogger())
            {
                if (logger.IsEnabled(LogEventLevel.Debug))
                {
                    logger.Debug(
                        "Running tool '{Deployer}' for deployment target '{DeploymentTarget}', package '{PackageId}' version {Version}",
                        _deployer,
                        deploymentTarget,
                        deploymentTask.PackageId,
                        deploymentTask.SemanticVersion.ToNormalizedString());
                }

                try
                {
                    exitCode = await _deployer.ExecuteAsync(deploymentTask, log, cancellationToken);
                }
                catch (Exception ex) when(!ex.IsFatal())
                {
                    _logger.Error(ex, "Failed to deploy task {DeploymentTask}", deploymentTask);
                    exitCode = ExitCode.Failure;
                }
            }

            DateTime finishedAtUtc = _customClock.UtcNow().UtcDateTime;

            await _mediator.Publish(
                new DeploymentFinishedNotification(deploymentTask, logBuilder.ToString(), finishedAtUtc),
                cancellationToken);

            return(exitCode, finishedAtUtc);
        }
 public DeploymentFinished(
     [NotNull] DeploymentTask deploymentTask,
     LogItem[] logLines,
     DateTime finishedAtUtc)
 {
     LogLines       = logLines.ToImmutableArray();
     FinishedAtUtc  = finishedAtUtc;
     DeploymentTask = deploymentTask ?? throw new ArgumentNullException(nameof(deploymentTask));
 }
示例#16
0
 public DeploymentFinishedNotification(
     [NotNull] DeploymentTask deploymentTask,
     string log,
     DateTime finishedAtUtc)
 {
     Log            = log;
     FinishedAtUtc  = finishedAtUtc;
     DeploymentTask = deploymentTask ?? throw new ArgumentNullException(nameof(deploymentTask));
 }
示例#17
0
 public void OnDeploymentTaskStarting(DeploymentInfo deploymentInfo, DeploymentTask deploymentTask, DeploymentContext deploymentContext)
 {
     if (deploymentInfo.TargetEnvironmentName == ProductionEnvironmentName &&
         deploymentInfo.ProjectConfigurationName != ProductionProjectConfigurationName)
     {
         throw new InvalidOperationException(string.Format(
                                                 "Can't deploy project ('{0}') with non-production configuration ('{1}') to the production environment!",
                                                 deploymentInfo.ProjectName,
                                                 deploymentInfo.ProjectConfigurationName));
     }
 }
示例#18
0
 public static Project ToProject(this DashboardItemResource dashboardItem, DeploymentTask currentDeploymentTask, DeploymentTask previousDeploymentTask)
 {
     return(new Project()
     {
         Id = dashboardItem.ProjectId,
         Name = $"Deploying {currentDeploymentTask.ProjectName} to {currentDeploymentTask.EnvironmentName}",
         Activity = ((TaskState)dashboardItem.State).ToActivity(),
         LastBuildStatus = ((TaskState)previousDeploymentTask.TaskResource.State).ToLastBuildStatus(),
         LastBuildLabel = previousDeploymentTask.ReleaseVersion,
         LastBuildTime = previousDeploymentTask.TaskResource.CompletedTime?.DateTime ?? DateTime.Now,
         WebUrl = dashboardItem.Links["Task"]
     });
 }
        public void StartDeployment(DeploymentInfo deploymentInfo, DeploymentTask deploymentTask, DeploymentContext deploymentContext, bool deployDependencies)
        {
            Guard.NotNull(deploymentInfo, "deploymentInfo");
            Guard.NotNull(deploymentTask, "deploymentTask");
            Guard.NotNull(deploymentContext, "deploymentContext");

            PostDiagnosticMessage(string.Format("Starting{0} '{1}'.", (deploymentInfo.IsSimulation ? " (simulation)" : ""), deploymentTask.GetType().Name), DiagnosticMessageType.Info);

            deploymentContext.DateStarted = DateTime.UtcNow;

            deploymentTask.DiagnosticMessagePosted += OnDeploymentTaskDiagnosticMessagePosted;

            bool finishedSuccessfully = false;

            OnDeploymentTaskStarting(deploymentInfo, deploymentTask, deploymentContext);

            try
            {
                deploymentTask.Initialize(deploymentInfo);

                if (_applicationConfiguration.DeployDependentProjects && deploymentInfo.ProjectConfigurationName == DeployDependenciesTask.DefaultTeamCityProjectConfiguration)
                {
                    deploymentTask.EnableDependenciesDeployment(_objectFactory);
                }

                deploymentTask.PrepareAndExecute();

                finishedSuccessfully = true;

                PostDiagnosticMessage(
                    string.Format("Finished{0} '{1}' (\"{2}\").", (deploymentInfo.IsSimulation ? " (simulation)" : ""),
                                  deploymentTask.GetType().Name, deploymentTask.Description), DiagnosticMessageType.Info);
                PostDiagnosticMessage(
                    "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -",
                    DiagnosticMessageType.Info);
            }
            catch (Exception ex)
            {
                PostDiagnosticMessage(string.Format("Exception: {0}", ex.Message), DiagnosticMessageType.Error);
            }
            finally
            {
                deploymentContext.DateFinished         = DateTime.UtcNow;
                deploymentContext.FinishedSuccessfully = finishedSuccessfully;

                // TODO IMM HI: catch exceptions; pass them upstream using some mechanisms like DeploymentTask.DiagnosticMessagePosted event
                OnDeploymentTaskFinished(deploymentInfo, deploymentTask, deploymentContext);

                deploymentTask.DiagnosticMessagePosted -= OnDeploymentTaskDiagnosticMessagePosted;
            }
        }
        public async Task <IActionResult> Index(DeploymentTaskInput?deploymentTaskInput)
        {
            if (deploymentTaskInput is null)
            {
                return(new StatusCodeResult((int)HttpStatusCode.BadRequest));
            }

            if (string.IsNullOrWhiteSpace(deploymentTaskInput.PackageId))
            {
                return(new StatusCodeResult((int)HttpStatusCode.BadRequest));
            }

            if (string.IsNullOrWhiteSpace(deploymentTaskInput.Version))
            {
                return(new StatusCodeResult((int)HttpStatusCode.BadRequest));
            }

            if (!SemanticVersion.TryParse(deploymentTaskInput.Version, out SemanticVersion semanticVersion))
            {
                return(new StatusCodeResult((int)HttpStatusCode.BadRequest));
            }

            if (deploymentTaskInput.TargetId == DeploymentTargetId.Invalid)
            {
                return(new StatusCodeResult((int)HttpStatusCode.BadRequest));
            }

            PackageVersion packageVersion = new(deploymentTaskInput.PackageId, semanticVersion);

            var deploymentTask = new DeploymentTask(packageVersion,
                                                    deploymentTaskInput.TargetId,
                                                    Guid.NewGuid(),
                                                    User?.Identity?.Name);

            try
            {
                await _deploymentService.Enqueue(deploymentTask);

                return(RedirectToAction(nameof(Status), new { deploymentTask.DeploymentTargetId }));
            }
            catch (Exception ex) when(!ex.IsFatal())
            {
                _logger.Error(ex, "Could not finish deploy of task {DeploymentTask}", deploymentTask);

                return(new ContentResult {
                    Content = ex.ToString(), StatusCode = 500
                });
            }
        }
示例#21
0
        public async Task <IDeploymentPackageAgent> GetAgentForDeploymentTask(
            DeploymentTask deploymentTask,
            CancellationToken cancellationToken)
        {
            while (_agents.Agents.Length == 0 && !cancellationToken.IsCancellationRequested)
            {
                _logger.Debug("Waiting for agents to connect");
                await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
            }

            while (!cancellationToken.IsCancellationRequested)
            {
                var availableAgents = _agents.Agents.Where(agent => agent.CurrentDeploymentTaskId is null).ToArray();

                var agentInfo = availableAgents.FirstOrDefault(); // improve algorithm to select agent

                if (agentInfo is { ConnectionId : { } })
        public DeploymentMetadataLog(
            [NotNull] DeploymentTask deploymentTask,
            [NotNull] DeploymentTaskResult result)
        {
            if (result is null)
            {
                throw new ArgumentNullException(nameof(result));
            }

            if (string.IsNullOrWhiteSpace(result.Metadata))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(result));
            }

            DeploymentTask = deploymentTask ?? throw new ArgumentNullException(nameof(deploymentTask));
            Result         = result;
        }
示例#23
0
        public void Enqueue([NotNull] DeploymentTask deploymentTask)
        {
            if (deploymentTask == null)
            {
                throw new ArgumentNullException(nameof(deploymentTask));
            }

            DeploymentTargetWorker foundWorker = GetWorkerByTargetId(deploymentTask.DeploymentTargetId);

            if (foundWorker is null)
            {
                throw new Core.DeployerAppException(
                          $"Could not find worker for deployment target id {deploymentTask.DeploymentTargetId}");
            }

            foundWorker.Enqueue(deploymentTask);
        }
示例#24
0
        public void OnDeploymentTaskFinished(DeploymentTask deploymentTask, DeploymentContext deploymentContext)
        {
            var deploymentRequest =
            new DeploymentRequest
              {
            RequesterIdentity = deploymentContext.RequesterIdentity,
            DateStarted = deploymentContext.DateStarted,
            DateFinished = deploymentContext.DateFinished,
            ProjectName = deploymentTask.ProjectName,
            ProjectConfigurationName = deploymentTask.ProjectConfigurationName,
            ProjectConfigurationBuildId = deploymentTask.ProjectConfigurationBuildId,
            TargetEnvironmentName = deploymentTask.TargetEnvironmentName,
            FinishedSuccessfully = deploymentContext.FinishedSuccessfully,
              };

              _deploymentRequestRepository.AddDeploymentRequest(deploymentRequest);
        }
        protected override async Task BeforeStartAsync(IReadOnlyCollection <string> args)
        {
            var deploymentService = App.AppRootScope.Deepest().Lifetime.Resolve <DeploymentService>();
            var readService       = App.AppRootScope.Deepest().Lifetime.Resolve <IDeploymentTargetReadService>();

            ImmutableArray <DeploymentTarget> targets = await readService.GetDeploymentTargetsAsync(CancellationToken);

            if (targets.Length != 1)
            {
                throw new DeployerAppException("The test target has not been created");
            }

            const string packageVersion = "MilouDeployerWebTest 1.2.4";

            Guid         deploymentTaskId   = Guid.NewGuid();
            const string deploymentTargetId = TestDataCreator.Testtarget;
            var          deploymentTask     = new DeploymentTask(packageVersion, deploymentTargetId, deploymentTaskId);

            DeploymentTaskResult deploymentTaskResult = await deploymentService.ExecuteDeploymentAsync(
                deploymentTask,
                App.Logger,
                App.CancellationTokenSource.Token);

            if (!deploymentTaskResult.ExitCode.IsSuccess)
            {
                throw new DeployerAppException($"Initial deployment failed, metadata: {deploymentTaskResult.Metadata}; test configuration: {TestConfiguration}");
            }

            TestStartup.TestConfiguration = TestConfiguration;

            _webHost = WebHost.CreateDefaultBuilder()
                       .UseKestrel(options =>
            {
                options.Listen(IPAddress.Loopback,
                               TestSiteHttpPort.Port);
            })
                       .UseContentRoot(TestConfiguration.SiteAppRoot.FullName)
                       .UseStartup <TestStartup>().Build();

            await _webHost.StartAsync(App.CancellationTokenSource.Token);

            CancellationToken.Register(() => _webHost.StopAsync());
        }
示例#26
0
        private void StartTask(DeploymentTask deploymentTask, Guid uniqueClientId, string requesterIdentity, Core.Domain.DeploymentInfo deploymentInfo)
        {
            var deploymentContext =
                new DeploymentContext(requesterIdentity);

            EventHandler <DiagnosticMessageEventArgs> deploymentPipelineDiagnosticMessageAction =
                (eventSender, tmpArgs) => LogMessage(uniqueClientId, tmpArgs.MessageType, tmpArgs.Message);

            try
            {
                _deploymentPipeline.DiagnosticMessagePosted += deploymentPipelineDiagnosticMessageAction;

                _deploymentPipeline.StartDeployment(deploymentInfo, deploymentTask, deploymentContext, _applicationConfiguration.DeployDependentProjects);
            }
            finally
            {
                _deploymentPipeline.DiagnosticMessagePosted -= deploymentPipelineDiagnosticMessageAction;
            }
        }
        public async Task TestDeployToKeyVault()
        {
            var deploymentTasks = new List <DeploymentTask>();

            var azureKeyVaultUri = ConfigSettings["Azure_TestKeyVaultUri"];
            var inputFile        = ConfigSettings["TestLocalPath"] + "\\testcert.pfx";

            var tasktypeId = Plugin.DeploymentTasks.Azure.AzureKeyVault.Definition.Id.ToLower();

            var config = new DeploymentTaskConfig
            {
                TaskTypeId        = tasktypeId,
                TaskName          = "A test pfx export task",
                ChallengeProvider = StandardAuthTypes.STANDARD_AUTH_LOCAL,

                Parameters = new List <ProviderParameterSetting>
                {
                    new ProviderParameterSetting("vault_uri", azureKeyVaultUri)
                }
            };

            var credentialsManager = new CredentialsManager();
            var credentials        = await credentialsManager.GetUnlockedCredentialsDictionary(ConfigSettings["TestCredentialsKey_AzureKeyVault"]);

            var provider = DeploymentTaskProviderFactory.Create(tasktypeId, _pluginManager.DeploymentTaskProviders);

            var t = new DeploymentTask(provider, config, credentials);

            deploymentTasks.Add(t);

            // perform preview deployments
            var managedCert = GetMockManagedCertificate("DeploymentTest", "123", PrimaryTestDomain, PrimaryIISRoot);

            managedCert.CertificatePath = inputFile;

            foreach (var task in deploymentTasks)
            {
                var results = await task.Execute(_log, null, managedCert, CancellationToken.None, new DeploymentContext { }, isPreviewOnly : false);

                // assert new valid pfx exists in destination
                Assert.IsTrue(results.All(r => r.IsSuccess));
            }
        }
        public async Task TestPemApacheExport()
        {
            var deploymentTasks = new List <DeploymentTask>();

            var outputPath = ConfigSettings["TestLocalPath"] + "\\test_pfx_export";

            var config = new DeploymentTaskConfig
            {
                TaskTypeId        = Certify.Providers.DeploymentTasks.Apache.Definition.Id.ToLower(),
                TaskName          = "A test Apache export task",
                ChallengeProvider = StandardAuthTypes.STANDARD_AUTH_LOCAL,

                Parameters = new List <ProviderParameterSetting>
                {
                    new ProviderParameterSetting("path_cert", outputPath + ".crt"),
                    new ProviderParameterSetting("path_key", outputPath + ".key"),
                    new ProviderParameterSetting("path_chain", outputPath + ".chain")
                }
            };

            var provider = DeploymentTaskProviderFactory.Create(Certify.Providers.DeploymentTasks.Apache.Definition.Id.ToLower(), _pluginManager.DeploymentTaskProviders);
            var t        = new DeploymentTask(provider, config, null);

            deploymentTasks.Add(t);

            // perform preview deployments
            var managedCert = GetMockManagedCertificate("LocalApacheDeploymentTest", "123", PrimaryTestDomain, PrimaryIISRoot);

            foreach (var task in deploymentTasks)
            {
                var result = await task.Execute(_log, null, managedCert, CancellationToken.None, new DeploymentContext { }, isPreviewOnly : false);
            }

            // assert output exists in destination
            Assert.IsTrue(File.Exists(outputPath + ".crt"));
            Assert.IsTrue(File.Exists(outputPath + ".key"));
            Assert.IsTrue(File.Exists(outputPath + ".chain"));

            File.Delete(outputPath + ".crt");
            File.Delete(outputPath + ".key");
            File.Delete(outputPath + ".chain");
        }
        public async Task TestServiceManagerValidation()
        {
            var taskTypeId = Certify.Providers.DeploymentTasks.ServiceManager.Definition.Id.ToLower();
            var provider   = DeploymentTaskProviderFactory.Create(taskTypeId, _pluginManager.DeploymentTaskProviders);

            var svcName = "aspnet_state";

            var restartTaskConfig = new DeploymentTaskConfig
            {
                TaskTypeId        = taskTypeId,
                TaskName          = "A test service manager task restart",
                ChallengeProvider = StandardAuthTypes.STANDARD_AUTH_LOCAL,

                Parameters = new List <ProviderParameterSetting>
                {
                    new ProviderParameterSetting("servicename", svcName),
                    new ProviderParameterSetting("action", "restart"),
                    new ProviderParameterSetting("maxwait", "20")
                }
            };

            var managedCert = GetMockManagedCertificate("Test", "123", PrimaryTestDomain, PrimaryIISRoot);

            List <ActionResult> results = new List <ActionResult>();
            var task = new DeploymentTask(provider, restartTaskConfig, null);

            var validationResult = await task.TaskProvider.Validate(
                new DeploymentTaskExecutionParams(
                    _log,
                    null,
                    managedCert,
                    task.TaskConfig,
                    null,
                    isPreviewOnly : false,
                    task.TaskProvider.GetDefinition(), CancellationToken.None,
                    new DeploymentContext {
            }
                    )
                );

            Assert.IsFalse(validationResult.Any());
        }
        private void ProcessInternal()
        {
            DeploymentTask temp = null;

            try
            {
                foreach (DeploymentTaskRequest request in _taskQueue.GetConsumingEnumerable(_cancellationSource.Token))
                {
                    temp = _builder.Build(request);
                    temp.Process();
                }
            }
            catch (OperationCanceledException)
            {
                //Operation canceled by cancellation source
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Error processing task '{0}'", temp.Name);
            }
        }
示例#31
0
        private async Task StartProcessingAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                DeploymentTask deploymentTask = _queue.Take(stoppingToken);

                deploymentTask.Status = WorkTaskStatus.Started;
                _runningTasks.Add(deploymentTask, stoppingToken);

                _logger.Information("Deployment target worker has taken {DeploymentTask}", deploymentTask);

                deploymentTask.Status = WorkTaskStatus.Started;

                _logger.Information("Executing deployment task {DeploymentTask}", deploymentTask);

                await Task.Delay(TimeSpan.FromMilliseconds(500), stoppingToken);

                DeploymentTaskResult result =
                    await _deploymentService.ExecuteDeploymentAsync(deploymentTask, _logger, stoppingToken);

                if (result.ExitCode.IsSuccess)
                {
                    _logger.Information("Executed deployment task {DeploymentTask}", deploymentTask);

                    deploymentTask.Status = WorkTaskStatus.Done;
                    deploymentTask.Log("{\"Message\": \"Work task completed\"}");
                }
                else
                {
                    _logger.Error("Failed to deploy task {DeploymentTask}, result {Result}",
                                  deploymentTask,
                                  result.Metadata);

                    deploymentTask.Status = WorkTaskStatus.Failed;
                    deploymentTask.Log("{\"Message\": \"Work task failed\"}");
                }
            }

            _queue?.Dispose();
        }
示例#32
0
        public void OnDeploymentTaskFinished(DeploymentInfo deploymentInfo, DeploymentTask deploymentTask, DeploymentContext deploymentContext)
        {
            if (deploymentInfo.IsSimulation || deploymentTask is CreateManualDeploymentPackageDeploymentTask)
              {
            return;
              }

              var deploymentRequest =
            new DeploymentRequest
              {
            RequesterIdentity = deploymentContext.RequesterIdentity,
            DateStarted = deploymentContext.DateStarted,
            DateFinished = deploymentContext.DateFinished,
            ProjectName = deploymentInfo.ProjectName,
            ProjectConfigurationName = deploymentInfo.ProjectConfigurationName,
            ProjectConfigurationBuildId = deploymentInfo.ProjectConfigurationBuildId,
            TargetEnvironmentName = deploymentInfo.TargetEnvironmentName,
            FinishedSuccessfully = deploymentContext.FinishedSuccessfully,
              };

              _deploymentRequestRepository.AddDeploymentRequest(deploymentRequest);
        }
示例#33
0
        public IActionResult Index(
            DeploymentTaskInput deploymentTaskInput)
        {
            if (deploymentTaskInput == null)
            {
                return(new StatusCodeResult((int)HttpStatusCode.BadRequest));
            }

            if (string.IsNullOrWhiteSpace(deploymentTaskInput.PackageVersion))
            {
                return(new StatusCodeResult((int)HttpStatusCode.BadRequest));
            }

            if (string.IsNullOrWhiteSpace(deploymentTaskInput.TargetId))
            {
                return(new StatusCodeResult((int)HttpStatusCode.BadRequest));
            }

            var deploymentTask = new DeploymentTask(deploymentTaskInput.PackageVersion,
                                                    deploymentTaskInput.TargetId,
                                                    Guid.NewGuid());

            try
            {
                _deploymentService.Enqueue(deploymentTask);

                return(RedirectToAction(nameof(Status), new { deploymentTask.DeploymentTargetId }));
            }
            catch (Exception ex) when(!ex.IsFatal())
            {
                _logger.Error(ex, "Could not finish deploy of task {DeploymentTask}", deploymentTask);

                return(new ContentResult
                {
                    Content = ex.ToString(),
                    StatusCode = 500
                });
            }
        }
示例#34
0
        public void Enqueue([NotNull] DeploymentTask deploymentTask)
        {
            if (deploymentTask == null)
            {
                throw new ArgumentNullException(nameof(deploymentTask));
            }

            try
            {
                using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)))
                {
                    DeploymentTask[] tasksInQueue = _queue.ToArray();

                    if (tasksInQueue.Length > 0 && tasksInQueue.Any(queued =>
                                                                    queued.PackageId.Equals(deploymentTask.PackageId, StringComparison.OrdinalIgnoreCase) &&
                                                                    queued.SemanticVersion.Equals(deploymentTask.SemanticVersion)))
                    {
                        _logger.Warning(
                            "A deployment task with package id {PackageId} and version {Version} is already enqueued, skipping task, , current queue length {Length}",
                            deploymentTask.PackageId,
                            deploymentTask.SemanticVersion.ToNormalizedString(),
                            tasksInQueue.Length);

                        return;
                    }

                    deploymentTask.Status = WorkTaskStatus.Enqueued;
                    _queue.Add(deploymentTask, cts.Token);

                    _logger.Information("Enqueued deployment task {DeploymentTask}, current queue length {Length}",
                                        deploymentTask,
                                        tasksInQueue);
                }
            }
            catch (Exception ex) when(!ex.IsFatal())
            {
                _logger.Error(ex, "Failed to enqueue deployment task {DeploymentTask}", deploymentTask);
            }
        }
        public void OnDeploymentTaskFinished(DeploymentInfo deploymentInfo, DeploymentTask deploymentTask, DeploymentContext deploymentContext)
        {
            if (deploymentInfo.IsSimulation || deploymentTask is CreateManualDeploymentPackageDeploymentTask)
            {
                return;
            }

            var deploymentRequest =
                new DeploymentRequest
            {
                RequesterIdentity           = deploymentContext.RequesterIdentity,
                DateStarted                 = deploymentContext.DateStarted,
                DateFinished                = deploymentContext.DateFinished,
                ProjectName                 = deploymentInfo.ProjectName,
                ProjectConfigurationName    = deploymentInfo.ProjectConfigurationName,
                ProjectConfigurationBuildId = deploymentInfo.ProjectConfigurationBuildId,
                TargetEnvironmentName       = deploymentInfo.TargetEnvironmentName,
                FinishedSuccessfully        = deploymentContext.FinishedSuccessfully,
            };

            _deploymentRequestRepository.AddDeploymentRequest(deploymentRequest);
        }
        public void StartDeployment(DeploymentInfo deploymentInfo, DeploymentTask deploymentTask, DeploymentContext deploymentContext)
        {
            Guard.NotNull(deploymentInfo, "deploymentInfo");
              Guard.NotNull(deploymentTask, "deploymentTask");
              Guard.NotNull(deploymentContext, "deploymentContext");

              PostDiagnosticMessage(string.Format("Starting{0} '{1}'.", (deploymentInfo.IsSimulation ? " (simulation)" : ""), deploymentTask.GetType().Name), DiagnosticMessageType.Info);

              deploymentContext.DateStarted = DateTime.UtcNow;

              deploymentTask.DiagnosticMessagePosted += OnDeploymentTaskDiagnosticMessagePosted;

              bool finishedSuccessfully = false;

              OnDeploymentTaskStarting(deploymentInfo, deploymentTask, deploymentContext);

              try
              {
            deploymentTask.Initialize(deploymentInfo);
            deploymentTask.PrepareAndExecute();

            finishedSuccessfully = true;

            PostDiagnosticMessage(string.Format("Finished{0} '{1}' (\"{2}\").", (deploymentInfo.IsSimulation ? " (simulation)" : ""), deploymentTask.GetType().Name, deploymentTask.Description), DiagnosticMessageType.Info);
            PostDiagnosticMessage("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -", DiagnosticMessageType.Info);
              }
              finally
              {
            deploymentContext.DateFinished = DateTime.UtcNow;
            deploymentContext.FinishedSuccessfully = finishedSuccessfully;

            // TODO IMM HI: catch exceptions; pass them upstream using some mechanisms like DeploymentTask.DiagnosticMessagePosted event
            OnDeploymentTaskFinished(deploymentInfo, deploymentTask, deploymentContext);

            deploymentTask.DiagnosticMessagePosted -= OnDeploymentTaskDiagnosticMessagePosted;
              }
        }
示例#37
0
 public void OnDeploymentTaskStarting(DeploymentInfo deploymentInfo, DeploymentTask deploymentTask, DeploymentContext deploymentContext)
 {
     // do nothing
 }
 public void OnDeploymentTaskFinished(DeploymentInfo deploymentInfo, DeploymentTask deploymentTask, DeploymentContext deploymentContext)
 {
     // do nothing
 }
 public ProjectDeploymentData(DeploymentInfo deploymentInfo, ProjectInfo projectInfo, DeploymentTask deploymentTask)
 {
     DeploymentTask = deploymentTask;
       DeploymentInfo = deploymentInfo;
       ProjectInfo = projectInfo;
 }
 private void OnDeploymentTaskFinished(DeploymentInfo deploymentInfo, DeploymentTask deploymentTask, DeploymentContext deploymentContext)
 {
     foreach (IDeploymentPipelineModule deploymentPipelineModule in _modules)
       {
     deploymentPipelineModule.OnDeploymentTaskFinished(deploymentInfo, deploymentTask, deploymentContext);
       }
 }