Exemple #1
0
        private async Task <EnvironmentDeployment> PrepareEnvironmentDeployment(Channel channel, Channel defaultChannel, OctoPlusCore.Models.Environment environment, IList <Project> projects, IEnumerable <int> indexes = null, bool all = false)
        {
            var deployment = new EnvironmentDeployment
            {
                ChannelName     = channel.Name,
                DeployAsync     = true,
                EnvironmentId   = environment.Id,
                EnvironmentName = environment.Name
            };

            if (all)
            {
                foreach (var project in projects)
                {
                    if (project.AvailablePackages.Any())
                    {
                        deployment.ProjectDeployments.Add(await GenerateProjectDeployment(channel, defaultChannel, project));
                    }
                }
            }
            else
            {
                foreach (var index in indexes)
                {
                    var current = projects[index];

                    if (current.AvailablePackages.Any())
                    {
                        deployment.ProjectDeployments.Add(await GenerateProjectDeployment(channel, defaultChannel, current));
                    }
                }
            }

            return(deployment);
        }
        public void PrintEnvironmentDeploy(EnvironmentDeployment environmentDeployment)
        {
            var name        = "EnvironmentDeployment";
            var description = "Environment Deployment";
            var timeStamp   = GetJavaTimeStamp();

            var environmentDeploymentJson = JsonConvert.SerializeObject(environmentDeployment, new JsonSerializerSettings {
                Formatting = Formatting.Indented
            });

            var openBlockMessage = _serviceMessageFormatter.FormatMessage("blockOpened", new
            {
                name        = name,
                description = description,
                flowId      = name,
                timeStamp   = timeStamp
            });

            var closeBlockMessage = _serviceMessageFormatter.FormatMessage("blockClosed", new
            {
                name      = name,
                flowId    = name,
                timeStamp = timeStamp
            });

            var message = openBlockMessage + Environment.NewLine + environmentDeploymentJson + Environment.NewLine + closeBlockMessage;

            Console.Out.WriteLine(message);
        }
Exemple #3
0
        private static int Deploy(INotifier notificaiton, ILogMessages logMessages, EnvironmentDeployment environmentDeployment, int maximumParalleDeployments, IEnumerable <IComponentVertexDeployer> deployers)
        {
            var cancellationTokenSource = new CancellationTokenSource();
            var deploymentExecutor      = new DeploymentExecutor(deployers, environmentDeployment, cancellationTokenSource.Token, logMessages, notificaiton, maximumParalleDeployments);
            var allDeploymentsSucceded  = deploymentExecutor.Execute().ConfigureAwait(false).GetAwaiter().GetResult();

            return(allDeploymentsSucceded ? 0 : 1);
        }
        public void PrintEnvironmentDeploy(EnvironmentDeployment environmentDeployment)
        {
            var environmentDeploymentJson = JsonConvert.SerializeObject(environmentDeployment, new JsonSerializerSettings {
                Formatting = Formatting.Indented
            });

            Console.Out.WriteLine(environmentDeploymentJson);
        }
        /// <summary>
        /// Deploy all products in parallel
        /// </summary>
        /// <param name="environmentDeployment"></param>
        /// <param name="cancellationToken"></param>
        /// <returns>True if all products were deployed successfully; else false</returns>
        private async Task <bool> DeployEnvironment(EnvironmentDeployment environmentDeployment, CancellationToken cancellationToken)
        {
            var productTasks = environmentDeployment.ProductDeployments
                               .Select(productDeployment => DeployProduct(productDeployment, cancellationToken));

            var productDeploymentResults = await WhenAll(productTasks, cancellationToken);

            return(productDeploymentResults != null && !productDeploymentResults.Any(x => x != true));
        }
 public DeploymentExecutor(IEnumerable <IComponentVertexDeployer> deployers, EnvironmentDeployment environmentDeployment, CancellationToken cancellationToken, ILogMessages logMessages, IProgress <ComponentVertexDeploymentProgress> progress, int maximumParallelDeployments = 4)
 {
     _deployers             = deployers;
     _environmentDeployment = environmentDeployment;
     _cancellationToken     = cancellationToken;
     _logMessages           = logMessages;
     _progress = progress;
     _maximumParallelDeployments = maximumParallelDeployments;
 }
Exemple #7
0
 private static void SetUpdateVariablesOnDeploymentPlan(EnvironmentDeployment environmentDeployment)
 {
     foreach (var vertex in from p in environmentDeployment.ProductDeployments
              from s in p.DeploymentSteps
              from c in s.ComponentDeployments
              select c.Vertex)
     {
         vertex.VariableAction = VariableAction.Update;
     }
 }
Exemple #8
0
        private static void SaveEnvironmentDeploy(string path, EnvironmentDeployment environmentDeployment)
        {
            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            var environmentDeploymentJson = JsonConvert.SerializeObject(environmentDeployment, new JsonSerializerSettings {
                Formatting = Formatting.Indented
            });

            File.WriteAllText(path, environmentDeploymentJson);
        }
Exemple #9
0
        private void SaveProfile(EnvironmentDeployment deployment, string profilePath)
        {
            foreach (var project in deployment.ProjectDeployments)
            {
                foreach (var package in project.Packages)
                {
                    package.PackageId   = "latest";
                    package.PackageName = "latest";
                }
            }
            var content = StandardSerialiser.SerializeToJsonNet(deployment, true);

            File.WriteAllText(profilePath, content);
            System.Console.WriteLine(string.Format(languageProvider.GetString(LanguageSection.UiStrings, "ProfileSaved"), profilePath));
        }
Exemple #10
0
        private async Task <bool> IsDeploymentRequired(EnvironmentDeployment job, ProjectDeployment project)
        {
            var needsDeploy    = false;
            var currentRelease = (await this.helper.GetReleasedVersion(project.ProjectId, job.EnvironmentId)).Release;

            if (currentRelease != null && !string.IsNullOrEmpty(currentRelease.Id))
            {
                // Check if we have any packages that are different versions. If they're the same, we don't need to deploy.
                foreach (var package in project.Packages)
                {
                    if (!currentRelease.SelectedPackages.Any(pack => pack.StepName == package.StepName && package.PackageName == pack.Version))
                    {
                        needsDeploy = true;
                    }
                }
            }
            return(needsDeploy);
        }
        public void BranchDeployment()
        {
            if (!CanBranchDeployment)
            {
                return;
            }

            IsLoadingData = true;
            Task.Factory.StartNew(() =>
            {
                try
                {
                    var deploymentPlanner = new OctopusDeploymentPlanner(_octopusUrl, _octopusApiKey);
                    var componentFilter   = new ComponentFilter
                    {
                        Expressions = ComponentFilterExpressions.Select(x => x.Text).ToList(),
                        Include     = ComponentFilterInclude
                    };

                    var branchDeploymentPlans = deploymentPlanner.GetBranchDeploymentPlans(_selectedBranchDeploymentEnvironment.Name, _selectedBranchDeploymentBranch.Name, _doNotUseDifferentialDeploymentForBranchDeployment, componentFilter);
                    EnvironmentDeploymentPlan = branchDeploymentPlans.EnvironmentDeploymentPlan;

                    var deploymentScheduler = new DeploymentScheduler();

                    var componentGraph = deploymentScheduler.GetComponentDeploymentGraph(EnvironmentDeploymentPlan);
                    Graph = componentGraph.ToBidirectionalGraph();
                    EnvironmentDeployment             = deploymentScheduler.GetEnvironmentDeployment(componentGraph);
                    EnvironmentDeploymentSaveFileName = "branch " + _selectedBranchDeploymentBranch.Name + " to " + _selectedBranchDeploymentEnvironment.Name + ".json";
                    EnvironmentToDeployTo             = _selectedBranchDeploymentEnvironment;
                }
                catch
                {
                    EnvironmentDeploymentPlan = new EnvironmentDeploymentPlan(new List <ComponentDeploymentPlan>());
                    Graph = null;
                    EnvironmentDeployment             = new EnvironmentDeployment(new List <ProductDeployment>());
                    EnvironmentDeploymentSaveFileName = string.Empty;
                    EnvironmentToDeployTo             = null;
                }
            }).ContinueWith(task =>
            {
                IsLoadingData = false;
            });
        }
Exemple #12
0
        protected async Task <bool> ValidateDeployment(EnvironmentDeployment deployment, IDeployer deployer)
        {
            if (deployment == null)
            {
                return(true);
            }

            var result = await deployer.CheckDeployment(deployment);

            if (result.Success)
            {
                return(true);
            }
            else
            {
                System.Console.WriteLine(languageProvider.GetString(LanguageSection.UiStrings, "Error") + result.ErrorMessage);
            }

            return(false);
        }
Exemple #13
0
        private async Task <EnvironmentDeployment> ExtractSelectedDeployment(bool saveProfile)
        {
            var deployment = new EnvironmentDeployment {
                EnvironmentId      = this.Environment.Id,
                EnvironmentName    = this.Environment.Name,
                ProjectDeployments = new List <ProjectDeployment>(),
                ChannelName        = this.Channel.Name,
                DeployAsync        = true
            };


            foreach (var item in this.ProjectList.Items)
            {
                var          project = (Project)item;
                ListViewItem lvi     = (ListViewItem)this.ProjectList.ItemContainerGenerator.ContainerFromItem(item);
                if (lvi != null)
                {
                    var comboBox = this.FindByName("packagecombo", lvi) as ComboBox;
                    var checkBox = this.FindByName("projectselectioncheckbox", lvi) as CheckBox;
                    if (checkBox.IsChecked.Value)
                    {
                        var channel = await this._helper.GetChannelByName(project.ProjectId, this.Channel.Name);

                        deployment.ProjectDeployments.Add(new ProjectDeployment
                        {
                            ProjectId           = project.ProjectId,
                            ProjectName         = project.ProjectName,
                            PackageId           = saveProfile ? "latest" : comboBox.SelectedValue.ToString(),
                            PackageName         = saveProfile ? "latest" : ((PackageStub)comboBox.SelectionBoxItem).Version,
                            StepName            = saveProfile ? "latest" : ((PackageStub)comboBox.SelectionBoxItem).StepName,
                            ChannelId           = channel.Id,
                            ChannelVersionRange = this.Channel.VersionRange,
                            LifeCycleId         = project.LifeCycleId
                        });
                    }
                }
            }
            return(deployment);
        }
Exemple #14
0
        private EnvironmentDeployment InteractivePrompt(OctoPlusCore.Models.Environment environment, OctoPlusCore.Models.Environment targetEnvironment, IList <Project> projects, IList <Project> targetProjects)
        {
            InteractiveRunner runner = PopulateRunner(String.Format(languageProvider.GetString(LanguageSection.UiStrings, "PromotingTo"), environment.Name, targetEnvironment.Name), projects, targetProjects);
            var indexes = runner.GetSelectedIndexes();

            if (!indexes.Any())
            {
                System.Console.WriteLine(languageProvider.GetString(LanguageSection.UiStrings, "NothingSelected"));
                return(null);
            }

            var deployment = new EnvironmentDeployment
            {
                ChannelName     = string.Empty,
                DeployAsync     = true,
                EnvironmentId   = targetEnvironment.Id,
                EnvironmentName = targetEnvironment.Name
            };

            foreach (var index in indexes)
            {
                var current       = projects[index];
                var currentTarget = targetProjects[index];

                if (current.CurrentRelease != null)
                {
                    deployment.ProjectDeployments.Add(new ProjectDeployment
                    {
                        ProjectId   = currentTarget.ProjectId,
                        ProjectName = currentTarget.ProjectName,
                        LifeCycleId = currentTarget.LifeCycleId,
                        ReleaseId   = current.CurrentRelease.Id
                    });
                }
            }

            return(deployment);
        }
Exemple #15
0
        public async Task <DeploymentCheckResult> CheckDeployment(EnvironmentDeployment deployment)
        {
            foreach (var project in deployment.ProjectDeployments)
            {
                var lifeCyle = await this.helper.GetLifeCycle(project.LifeCycleId);

                if (lifeCyle.Phases.Any())
                {
                    var safe = false;
                    if (lifeCyle.Phases[0].OptionalDeploymentTargetEnvironmentIds.Any())
                    {
                        if (lifeCyle.Phases[0].OptionalDeploymentTargetEnvironmentIds.Contains(deployment.EnvironmentId))
                        {
                            safe = true;
                        }
                    }
                    if (!safe && lifeCyle.Phases[0].AutomaticDeploymentTargetEnvironmentIds.Any())
                    {
                        if (lifeCyle.Phases[0].AutomaticDeploymentTargetEnvironmentIds.Contains(deployment.EnvironmentId))
                        {
                            safe = true;
                        }
                    }
                    if (!safe)
                    {
                        var phaseCheck  = true;
                        var deployments = await this.helper.GetDeployments(project.ReleaseId);

                        var previousEnvs = deployments.Select(d => d.EnvironmentId);
                        foreach (var phase in lifeCyle.Phases)
                        {
                            if (!phase.Optional)
                            {
                                if (phase.MinimumEnvironmentsBeforePromotion == 0)
                                {
                                    if (!previousEnvs.All(e => phase.OptionalDeploymentTargetEnvironmentIds.Contains(e)) && !phase.OptionalDeploymentTargetEnvironmentIds.Contains(deployment.EnvironmentId))
                                    {
                                        phaseCheck = false;
                                        break;
                                    }
                                }
                                else
                                {
                                    if (phase.MinimumEnvironmentsBeforePromotion > previousEnvs.Intersect(phase.OptionalDeploymentTargetEnvironmentIds).Count())
                                    {
                                        phaseCheck = false;
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                continue;
                            }
                        }
                        safe = phaseCheck;
                    }
                    if (!safe)
                    {
                        return(new DeploymentCheckResult {
                            Success = false,
                            ErrorMessage = DeploymentStrings.FailedValidation.Replace("{{projectname}}", project.ProjectName).Replace("{{environmentname}}", deployment.EnvironmentName)
                        });
                    }
                }
            }
            return(new DeploymentCheckResult {
                Success = true
            });
        }
Exemple #16
0
        private async Task ProcessEnvironmentDeployment(EnvironmentDeployment deployment, bool suppressMessages,
                                                        IUiLogger uiLogger)
        {
            uiLogger.WriteLine("Starting deployment!");
            var failedProjects = new Dictionary <ProjectDeployment, TaskDetails>();

            var taskRegister    = new Dictionary <string, TaskDetails>();
            var projectRegister = new Dictionary <string, ProjectDeployment>();

            foreach (var project in deployment.ProjectDeployments)
            {
                Release result;
                if (string.IsNullOrEmpty(project.ReleaseId))
                {
                    uiLogger.WriteLine("Creating a release for project " + project.ProjectName + "... ");
                    result = await helper.CreateRelease(project, deployment.FallbackToDefaultChannel);
                }
                else
                {
                    uiLogger.WriteLine("Fetching existing release for project " + project.ProjectName + "... ");
                    result = await helper.GetRelease(project.ReleaseId);
                }

                uiLogger.WriteLine("Creating deployment task for " + result.Version + " to " + deployment.EnvironmentName);
                var deployResult = await helper.CreateDeploymentTask(project, deployment.EnvironmentId, result.Id);

                uiLogger.WriteLine("Created");

                var taskDeets = await helper.GetTaskDetails(deployResult.TaskId);

                //taskDeets = await StartDeployment(uiLogger, taskDeets, !deployment.DeployAsync);
                if (deployment.DeployAsync)
                {
                    taskRegister.Add(taskDeets.TaskId, taskDeets);
                    projectRegister.Add(taskDeets.TaskId, project);
                }
                else
                {
                    if (taskDeets.State == Models.TaskStatus.Failed)
                    {
                        uiLogger.WriteLine("Failed deploying " + project.ProjectName);
                        failedProjects.Add(project, taskDeets);
                    }
                    uiLogger.WriteLine("Deployed!");
                    uiLogger.WriteLine("Full Log: " + System.Environment.NewLine +
                                       await this.helper.GetTaskRawLog(taskDeets.TaskId));
                    taskDeets = await helper.GetTaskDetails(deployResult.TaskId);
                }
            }


            // This needs serious improvement.
            if (deployment.DeployAsync)
            {
                await DeployAsync(uiLogger, failedProjects, taskRegister, projectRegister);
            }

            uiLogger.WriteLine("Done deploying!");
            if (failedProjects.Any())
            {
                uiLogger.WriteLine("Some projects didn't deploy successfully: ");
                foreach (var failure in failedProjects)
                {
                    var link = string.Empty;
                    if (failure.Value.Links != null)
                    {
                        if (failure.Value.Links.ContainsKey("Web"))
                        {
                            link = configuration.OctopusUrl + failure.Value.Links["Web"];
                        }
                    }
                    uiLogger.WriteLine(failure.Key.ProjectName + ": " + link);
                }
            }
            if (!suppressMessages)
            {
                uiLogger.WriteLine("Done deploying!" +
                                   (failedProjects.Any() ? " There were failures though. Check the log." : string.Empty));
            }
        }