Exemplo n.º 1
0
        private async Task BuildClientProject(ProjectGroupResource projectGroup, LifecycleResource normalLifecycle)
        {
            var clientProjectEditor = await Repository.Projects.CreateOrModify("Truck Tracker Client", projectGroup, normalLifecycle);

            clientProjectEditor.SetLogo(SampleImageCache.DownloadImage("http://b2bimg.bridgat.com/files/GPS_Camera_TrackerGPS_Camera_Tracking.jpg", "GPS_Camera_TrackerGPS_Camera_Tracking.jpg"));

            var variables = await clientProjectEditor.Variables;

            variables.AddOrUpdateVariableValue("TrackerUrl", "https://trucktracker.com/trucks/#{Octopus.Machine.Name}");

            var channel = await clientProjectEditor.Channels.CreateOrModify("1.x Normal", "The channel for stable releases that will be deployed to our production trucks.");

            channel.SetAsDefaultChannel();

            await clientProjectEditor.Channels.Delete("Default");

            var deploymentProcess = await clientProjectEditor.DeploymentProcess;

            deploymentProcess.AddOrUpdateStep("Deploy Application")
            .TargetingRoles("truck")
            .AddOrUpdateScriptAction("Deploy Application", new InlineScriptActionFromFileInAssembly("TrucksSample.Client.Deploy.fsx"), ScriptTarget.Target);

            await clientProjectEditor.Triggers.CreateOrModify("Auto-Deploy to trucks when available",
                                                              ProjectTriggerType.DeploymentTarget,
                                                              ProjectTriggerConditionEvent.ExistingDeploymentTargetChangesState,
                                                              ProjectTriggerConditionEvent.NewDeploymentTargetBecomesAvailable);

            await clientProjectEditor.Save();
        }
        protected override void ProcessRecord()
        {
            object baseresource = null;

            switch (Resource)
            {
            case "Environment":
                baseresource = new EnvironmentResource();
                break;

            case "Project":
                baseresource = new ProjectResource();
                break;

            case "ProjectGroup":
                baseresource = new ProjectGroupResource();
                break;

            case "NugetFeed":
            case "ExternalFeed":
                baseresource = new NuGetFeedResource();
                break;

            case "LibraryVariableSet":
                baseresource = new LibraryVariableSetResource();
                break;

            case "Machine":
            case "Target":
                baseresource = new MachineResource();
                break;

            case "Lifecycle":
                baseresource = new LifecycleResource();
                break;

            case "Team":
                baseresource = new TeamResource();
                break;

            case "User":
                baseresource = new UserResource();
                break;

            case "Channel":
                baseresource = new ChannelResource();
                break;

            case "Tenant":
                baseresource = new TenantResource();
                break;

            case "TagSet":
                baseresource = new TagSetResource();
                break;
            }

            WriteObject(baseresource);
        }
Exemplo n.º 3
0
 public static async Task <Lifecycle> ToModel(this LifecycleResource resource, IOctopusAsyncRepository repository)
 {
     return(new Lifecycle(
                new ElementIdentifier(resource.Name),
                resource.Description,
                resource.ReleaseRetentionPolicy.ToModel(),
                resource.TentacleRetentionPolicy.ToModel(),
                await Task.WhenAll(resource.Phases.Select(phase => phase.ToModel(repository)))));
 }
Exemplo n.º 4
0
        /// <summary>
        /// Creates a LifeCycle
        /// </summary>
        /// <param name="octRepository">The repository to call against.</param>
        /// <param name="lifecycleName">Name of the Lifecycle to create.</param>
        /// <returns></returns>
        public static LifecycleResource CreateLifeCycle(OctopusRepository octRepository, string lifecycleName)
        {
            var lifecycle = new LifecycleResource()
            {
                Name = lifecycleName
            };

            return(octRepository.Lifecycles.Create(lifecycle));
        }
Exemplo n.º 5
0
        public void CreateAndRemoveLifecycle()
        {
            #region LifecycleCreate

            var releaseRetention  = new RetentionPeriod(1, RetentionUnit.Items);
            var tentacleRetention = new RetentionPeriod(1, RetentionUnit.Items);

            var resource = new LifecycleResource()
            {
                Name                    = TestResourceName,
                Description             = String.Format("Lifecycle {0}", TestResourceName),
                ReleaseRetentionPolicy  = releaseRetention,
                TentacleRetentionPolicy = tentacleRetention
            };

            var createParameters = new List <CmdletParameter>
            {
                new CmdletParameter()
                {
                    Name     = "Resource",
                    Resource = resource
                }
            };

            var createPowershell = new CmdletRunspace().CreatePowershellcmdlet(CreateCmdletName, CreateCmdletType, createParameters);

            //The fact that the line below doesn't throw is enough to prove that the cmdlet returns the expected object type really. Couldn't figure out a way to make the assert around the Powershell.invoke call
            var createResult = createPowershell.Invoke <LifecycleResource>().FirstOrDefault();

            if (createResult != null)
            {
                Assert.AreEqual(createResult.Name, TestResourceName);
                Console.WriteLine("Created resource [{0}] of type [{1}]", createResult.Name, createResult.GetType());
            }
            #endregion

            #region LifecycleDelete
            var removeParameters = new List <CmdletParameter>
            {
                new CmdletParameter()
                {
                    Name     = "Resource",
                    Resource = createResult
                }
            };

            var removePowershell = new CmdletRunspace().CreatePowershellcmdlet(RemoveCmdletName, RemoveCmdletType);

            var removeResult = removePowershell.Invoke <bool>(removeParameters).FirstOrDefault();

            Assert.IsTrue(removeResult);
            Console.WriteLine("Deleted resource [{0}] of type [{1}]", createResult.Name, createResult.GetType());
            #endregion
        }
Exemplo n.º 6
0
        private async Task BuildServerProject(ProjectGroupResource projectGroup, LifecycleResource normalLifecycle)
        {
            var serverProjectEditor = await Repository.Projects.CreateOrModify("Truck Tracker Server", projectGroup, normalLifecycle);

            serverProjectEditor.SetLogo(SampleImageCache.DownloadImage("http://blog.budgettrucks.com.au/wp-content/uploads/2015/08/tweed-heads-moving-truck-rental-map.jpg"));

            (await serverProjectEditor.Variables).AddOrUpdateVariableValue("DatabaseConnectionString", $"Server=trackerdb.com;Database=trackerdb;");
            (await serverProjectEditor.DeploymentProcess).AddOrUpdateStep("Deploy Application")
            .AddOrUpdateScriptAction("Deploy Application", new InlineScriptActionFromFileInAssembly("TrucksSample.Server.Deploy.fsx"), ScriptTarget.Server);

            await serverProjectEditor.Save();
        }
Exemplo n.º 7
0
 public static async Task <LifecycleResource> UpdateWith(this LifecycleResource resource, Lifecycle model, IOctopusAsyncRepository repository)
 {
     resource.Name                    = model.Identifier.Name;
     resource.Description             = model.Description;
     resource.ReleaseRetentionPolicy  = model.ReleaseRetentionPolicy.FromModel();
     resource.TentacleRetentionPolicy = model.TentacleRetentionPolicy.FromModel();
     resource.Phases.Clear();
     foreach (var phase in model.Phases)
     {
         resource.Phases.Add(await new PhaseResource().UpdateWith(phase, repository));
     }
     return(resource);
 }
Exemplo n.º 8
0
        private LifecycleResource CreateLifecycle(int id, IEnumerable <EnvironmentResource> environments)
        {
            var lc = new LifecycleResource()
            {
                Name = "Life" + id.ToString("000"),
            };

            lc.Phases.Add(new PhaseResource()
            {
                Name = "AllTheEnvs",
                OptionalDeploymentTargets = new ReferenceCollection(environments.Select(ef => ef.Id))
            });
            return(Repository.Lifecycles.Create(lc));
        }
Exemplo n.º 9
0
        private void CreateProjects(int prefix, ProjectGroupResource group, LifecycleResource lifecycle)
        {
            var numberOfProjects = ProjectsPerGroup.Get();

            Log.Information("Creating {n} projects for {group}", numberOfProjects, group.Name);
            Enumerable.Range(1, numberOfProjects)
            .AsParallel()
            .ForAll(p =>
            {
                var project = CreateProject(group, lifecycle, $"-{prefix:000}-{p:00}");
                UpdateDeploymentProcess(project);
                CreateChannels(project, lifecycle);
                SetVariables(project);
                Log.Information("Created project {name}", project.Name);
            }
                    );
        }
Exemplo n.º 10
0
        private void CreateChannels(ProjectResource project, LifecycleResource lifecycle)
        {
            var numberOfExtraChannels = ExtraChannelsPerProject.Get();

            Enumerable.Range(1, numberOfExtraChannels)
            .AsParallel()
            .ForAll(p =>
                    Repository.Channels.Create(new ChannelResource()
            {
                LifecycleId = lifecycle.Id,
                ProjectId   = project.Id,
                Name        = "Channel " + p.ToString("000"),
                Rules       = new List <ChannelVersionRuleResource>(),
                IsDefault   = false
            })
                    );
        }
Exemplo n.º 11
0
        LifecycleResource CheckProjectLifecycle(ReferenceDataItem lifecycle)
        {
            var existingLifecycles = Repository.Lifecycles.FindAll();

            if (existingLifecycles.Count == 0)
            {
                return(null);
            }

            LifecycleResource existingLifecycle = null;

            if (lifecycle != null)
            {
                Log.DebugFormat("Checking that lifecycle {0} exists", lifecycle.Name);
                existingLifecycle = existingLifecycles.Find(lc => lc.Name == lifecycle.Name);
                if (existingLifecycle == null)
                {
                    Log.DebugFormat("Lifecycle {0} does not exist, default lifecycle will be used instead", lifecycle.Name);
                }
            }

            return(existingLifecycle ?? existingLifecycles.FirstOrDefault());
        }
        protected async Task <LifecycleResource> CheckProjectLifecycle(ReferenceDataItem lifecycle)
        {
            var existingLifecycles = await Repository.Lifecycles.FindAll().ConfigureAwait(false);

            if (existingLifecycles.Count == 0)
            {
                return(null);
            }

            LifecycleResource existingLifecycle = null;

            if (lifecycle != null)
            {
                Log.Debug("Checking that lifecycle {Lifecycle:l} exists", lifecycle.Name);
                existingLifecycle = existingLifecycles.Find(lc => lc.Name == lifecycle.Name);
                if (existingLifecycle == null)
                {
                    Log.Debug("Lifecycle {Lifecycle:l} does not exist, default lifecycle will be used instead", lifecycle.Name);
                }
            }

            return(existingLifecycle ?? existingLifecycles.FirstOrDefault());
        }
Exemplo n.º 13
0
        private ProjectResource CreateProject(ProjectGroupResource group, LifecycleResource lifecycle, string postfix)
        {
            var project = Repository.Projects.Create(new ProjectResource()
            {
                Name           = "Project" + postfix,
                Description    = @"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?",
                ProjectGroupId = group.Id,
                LifecycleId    = lifecycle.Id,
            });

            //try
            //{
            //    using (var ms = new MemoryStream(CreateLogo(project.Name, "monsterid")))
            //        Repository.Projects.SetLogo(project, project.Name + ".png", ms);
            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine($"Failed to create logo for {project.Name}", ex);
            //}

            return(project);
        }
Exemplo n.º 14
0
        private LifeCycle ConvertLifeCycle(LifecycleResource lifeCycle)
        {
            var lc = new LifeCycle
            {
                Name        = lifeCycle.Name,
                Id          = lifeCycle.Id,
                Description = lifeCycle.Description
            };

            if (lifeCycle.Phases != null)
            {
                foreach (var phase in lifeCycle.Phases)
                {
                    var newPhase = new Phase
                    {
                        Name = phase.Name,
                        Id   = phase.Id,
                        MinimumEnvironmentsBeforePromotion = phase.MinimumEnvironmentsBeforePromotion,
                        Optional = phase.IsOptionalPhase
                    };
                    if (phase.OptionalDeploymentTargets != null)
                    {
                        newPhase.OptionalDeploymentTargetEnvironmentIds = phase.OptionalDeploymentTargets.ToList();
                    }
                    if (phase.AutomaticDeploymentTargets != null)
                    {
                        newPhase.AutomaticDeploymentTargetEnvironmentIds = phase.AutomaticDeploymentTargets.ToList();
                    }
                    if (newPhase.AutomaticDeploymentTargetEnvironmentIds.Any() || newPhase.OptionalDeploymentTargetEnvironmentIds.Any())
                    {
                        lc.Phases.Add(newPhase);
                    }
                }
            }
            return(lc);
        }
Exemplo n.º 15
0
 private async Task <Lifecycle> ReadLifecycle(LifecycleResource resource)
 {
     _logger.LogInformation($"Downloading {nameof(LifecycleResource)}: {resource.Name}");
     return(await resource.ToModel(_repository));
 }
Exemplo n.º 16
0
 public ProjectEditor CreateOrModify(string name, ProjectGroupResource projectGroup, LifecycleResource lifecycle, string description, string cloneId = null)
 {
     return(new ProjectEditor(this, new ChannelRepository(Repository), new DeploymentProcessRepository(Repository), new ProjectTriggerRepository(Repository), new VariableSetRepository(Repository)).CreateOrModify(name, projectGroup, lifecycle, description, cloneId));
 }
Exemplo n.º 17
0
 public Task <ProjectEditor> CreateOrModify(string name, ProjectGroupResource projectGroup, LifecycleResource lifecycle)
 {
     return(new ProjectEditor(this, new ChannelRepository(Client), new DeploymentProcessRepository(Client), new ProjectTriggerRepository(Client), new VariableSetRepository(Client)).CreateOrModify(name, projectGroup, lifecycle));
 }
Exemplo n.º 18
0
 public ChannelEditor UsingLifecycle(LifecycleResource lifecycle)
 {
     Instance.UsingLifecycle(lifecycle);
     return(this);
 }
Exemplo n.º 19
0
        protected override async Task Export(Dictionary <string, string> parameters)
        {
            if (string.IsNullOrWhiteSpace(parameters["Name"]))
            {
                throw new CommandException("Please specify the name of the project to export using the parameter: --name=XYZ");
            }

            var projectName = parameters["Name"];

            Log.Debug("Finding project: {Project:l}", projectName);
            var project = await Repository.Projects.FindByName(projectName).ConfigureAwait(false);

            if (project == null)
            {
                throw new CouldNotFindException("a project named", projectName);
            }

            Log.Debug("Finding project group for project");
            var projectGroup = await Repository.ProjectGroups.Get(project.ProjectGroupId).ConfigureAwait(false);

            if (projectGroup == null)
            {
                throw new CouldNotFindException("project group for project", project.Name);
            }

            Log.Debug("Finding variable set for project");
            var variables = await Repository.VariableSets.Get(project.VariableSetId).ConfigureAwait(false);

            if (variables == null)
            {
                throw new CouldNotFindException("variable set for project", project.Name);
            }

            var channelLifecycles = new List <ReferenceDataItem>();
            var channels          = new ChannelResource[0];

            if (Repository.SupportsChannels())
            {
                Log.Debug("Finding channels for project");
                var firstChannelPage = await Repository.Projects.GetChannels(project).ConfigureAwait(false);

                channels = (await firstChannelPage.GetAllPages(Repository).ConfigureAwait(false)).ToArray();

                foreach (var channel in channels.ToArray())
                {
                    if (channel.LifecycleId != null)
                    {
                        var channelLifecycle = await Repository.Lifecycles.Get(channel.LifecycleId).ConfigureAwait(false);

                        if (channelLifecycle == null)
                        {
                            throw new CouldNotFindException("Lifecycle for channel", channel.Name);
                        }
                        if (channelLifecycles.All(cl => cl.Id != channelLifecycle.Id))
                        {
                            channelLifecycles.Add(new ReferenceDataItem(channelLifecycle.Id, channelLifecycle.Name));
                        }
                    }
                }
            }

            Log.Debug("Finding deployment process for project");
            var deploymentProcess = await Repository.DeploymentProcesses.Get(project.DeploymentProcessId).ConfigureAwait(false);

            if (deploymentProcess == null)
            {
                throw new CouldNotFindException("deployment process for project", project.Name);
            }

            Log.Debug("Finding NuGet feed for deployment process...");
            var nugetFeeds = new List <ReferenceDataItem>();

            foreach (var step in deploymentProcess.Steps)
            {
                foreach (var action in step.Actions)
                {
                    PropertyValueResource nugetFeedId;
                    if (action.Properties.TryGetValue("Octopus.Action.Package.NuGetFeedId", out nugetFeedId))
                    {
                        Log.Debug("Finding NuGet feed for step {StepName:l}", step.Name);
                        FeedResource feed = null;
                        if (FeedCustomExpressionHelper.IsRealFeedId(nugetFeedId.Value))
                        {
                            feed = await Repository.Feeds.Get(nugetFeedId.Value).ConfigureAwait(false);
                        }
                        else
                        {
                            feed = FeedCustomExpressionHelper.CustomExpressionFeedWithId(nugetFeedId.Value);
                        }

                        if (feed == null)
                        {
                            throw new CouldNotFindException("NuGet feed for step", step.Name);
                        }

                        if (nugetFeeds.All(f => f.Id != nugetFeedId.Value))
                        {
                            nugetFeeds.Add(new ReferenceDataItem(feed.Id, feed.Name));
                        }
                    }
                }
            }

            Log.Debug("Finding action templates for project");
            var actionTemplates = new List <ReferenceDataItem>();

            foreach (var step in deploymentProcess.Steps)
            {
                foreach (var action in step.Actions)
                {
                    PropertyValueResource templateId;
                    if (action.Properties.TryGetValue("Octopus.Action.Template.Id", out templateId))
                    {
                        Log.Debug("Finding action template for step {StepName:l}", step.Name);
                        var template = await actionTemplateRepository.Get(templateId.Value).ConfigureAwait(false);

                        if (template == null)
                        {
                            throw new CouldNotFindException("action template for step", step.Name);
                        }
                        if (actionTemplates.All(t => t.Id != templateId.Value))
                        {
                            actionTemplates.Add(new ReferenceDataItem(template.Id, template.Name));
                        }
                    }
                }
            }

            var libraryVariableSets = new List <ReferenceDataItem>();

            foreach (var libraryVariableSetId in project.IncludedLibraryVariableSetIds)
            {
                var libraryVariableSet = await Repository.LibraryVariableSets.Get(libraryVariableSetId).ConfigureAwait(false);

                if (libraryVariableSet == null)
                {
                    throw new CouldNotFindException("library variable set with Id", libraryVariableSetId);
                }
                libraryVariableSets.Add(new ReferenceDataItem(libraryVariableSet.Id, libraryVariableSet.Name));
            }

            LifecycleResource lifecycle = null;

            if (project.LifecycleId != null)
            {
                lifecycle = await Repository.Lifecycles.Get(project.LifecycleId).ConfigureAwait(false);

                if (lifecycle == null)
                {
                    throw new CouldNotFindException($"lifecycle with Id {project.LifecycleId} for project ", project.Name);
                }
            }

            var export = new ProjectExport
            {
                Project             = project,
                ProjectGroup        = new ReferenceDataItem(projectGroup.Id, projectGroup.Name),
                VariableSet         = variables,
                DeploymentProcess   = deploymentProcess,
                NuGetFeeds          = nugetFeeds,
                ActionTemplates     = actionTemplates,
                LibraryVariableSets = libraryVariableSets,
                Lifecycle           = lifecycle != null ? new ReferenceDataItem(lifecycle.Id, lifecycle.Name) : null,
                Channels            = channels.ToList(),
                ChannelLifecycles   = channelLifecycles,
            };

            var metadata = new ExportMetadata
            {
                ExportedAt     = DateTime.Now,
                OctopusVersion = Repository.Client.RootDocument.Version,
                Type           = typeof(ProjectExporter).GetAttributeValue((ExporterAttribute ea) => ea.Name),
                ContainerType  = typeof(ProjectExporter).GetAttributeValue((ExporterAttribute ea) => ea.EntityType)
            };

            FileSystemExporter.Export(FilePath, metadata, export);
        }
Exemplo n.º 20
0
        public async Task Request()
        {
            if (!await Repository.SupportsChannels().ConfigureAwait(false))
            {
                throw new CommandException("Your Octopus Server does not support channels, which was introduced in Octopus 3.2. Please upgrade your Octopus Server to start using channels.");
            }
            if (string.IsNullOrWhiteSpace(projectName))
            {
                throw new CommandException("Please specify a project using the parameter: --project=ProjectXYZ");
            }
            if (string.IsNullOrWhiteSpace(channelName))
            {
                throw new CommandException("Please specify a channel name using the parameter: --channel=ChannelXYZ");
            }

            commandOutputProvider.Debug("Loading project {Project:l}...", projectName);

            project = await Repository.Projects.FindByName(projectName).ConfigureAwait(false);

            if (project == null)
            {
                throw new CouldNotFindException("project named", projectName);
            }

            lifecycle = null;
            if (string.IsNullOrWhiteSpace(lifecycleName))
            {
                commandOutputProvider.Debug("No lifecycle specified. Going to inherit the project lifecycle...");
            }
            else
            {
                commandOutputProvider.Debug("Loading lifecycle {Lifecycle:l}...", lifecycleName);
                lifecycle = await Repository.Lifecycles.FindOne(l => string.Compare(l.Name, lifecycleName, StringComparison.OrdinalIgnoreCase) == 0).ConfigureAwait(false);

                if (lifecycle == null)
                {
                    throw new CouldNotFindException("lifecycle named", lifecycleName);
                }
            }

            var channels = await Repository.Projects.GetChannels(project).ConfigureAwait(false);

            channel = await channels
                      .FindOne(Repository, ch => string.Equals(ch.Name, channelName, StringComparison.OrdinalIgnoreCase)).ConfigureAwait(false);

            if (channel == null)
            {
                createdNewChannel = true;
                channel           = new ChannelResource
                {
                    ProjectId   = project.Id,
                    Name        = channelName,
                    IsDefault   = makeDefaultChannel ?? false,
                    Description = channelDescription ?? string.Empty,
                    LifecycleId = lifecycle?.Id, // Allow for the default lifeycle by propagating null
                    Rules       = new List <ChannelVersionRuleResource>(),
                };

                commandOutputProvider.Debug("Creating channel {Channel:l}", channelName);
                await Repository.Channels.Create(channel).ConfigureAwait(false);

                commandOutputProvider.Information("Channel {Channel:l} created", channelName);
                return;
            }

            if (!updateExisting)
            {
                throw new CommandException("This channel already exists. If you would like to update it, please use the parameter: --update-existing");
            }

            channelUpdateRequired = false;
            if (channel.LifecycleId != lifecycle?.Id)
            {
                if (lifecycle == null)
                {
                    commandOutputProvider.Information("Updating this channel to inherit the project lifecycle for promoting releases");
                }
                else
                {
                    commandOutputProvider.Information("Updating this channel to use lifecycle {Lifecycle:l} for promoting releases", lifecycle.Name);
                }

                channel.LifecycleId   = lifecycle?.Id;
                channelUpdateRequired = true;
            }

            if (!channel.IsDefault && makeDefaultChannel == true)
            {
                commandOutputProvider.Information("Making this the default channel for {Project:l}", project.Name);
                channel.IsDefault     = makeDefaultChannel ?? channel.IsDefault;
                channelUpdateRequired = true;
            }

            if (!string.IsNullOrWhiteSpace(channelDescription) && channel.Description != channelDescription)
            {
                commandOutputProvider.Information("Updating channel description to '{Description:l}'", channelDescription);
                channel.Description   = channelDescription ?? channel.Description;
                channelUpdateRequired = true;
            }

            if (!channelUpdateRequired)
            {
                commandOutputProvider.Information("The channel already looks exactly the way it should, no need to update it.");
                return;
            }

            commandOutputProvider.Debug("Updating channel {Channel:l}", channelName);
            await Repository.Channels.Modify(channel).ConfigureAwait(false);

            commandOutputProvider.Information("Channel {Channel:l} updated", channelName);
        }
 private Lifecycle ReadLifecycle(LifecycleResource resource)
 {
     Logger.Info($"Downloading {nameof(LifecycleResource)}: {resource.Name}");
     return(resource.ToModel(_repository));
 }
Exemplo n.º 22
0
        public ProjectEditor CreateOrModify(string name, ProjectGroupResource projectGroup, LifecycleResource lifecycle, string description, string cloneId)
        {
            var existing = repository.FindByName(name);

            if (existing == null)
            {
                Instance = repository.Create(new ProjectResource
                {
                    Name           = name,
                    ProjectGroupId = projectGroup.Id,
                    LifecycleId    = lifecycle.Id,
                    Description    = description
                }, new { clone = cloneId });
            }
            else
            {
                existing.Name           = name;
                existing.ProjectGroupId = projectGroup.Id;
                existing.LifecycleId    = lifecycle.Id;
                existing.Description    = description;

                Instance = repository.Modify(existing);
            }

            return(this);
        }
Exemplo n.º 23
0
 public ProjectEditor CreateOrModify(string name, ProjectGroupResource projectGroup, LifecycleResource lifecycle, string description)
 {
     throw new NotImplementedException();
 }
        private async Task BuildProject(
            ProjectGroupResource projectGroup,
            LifecycleResource normalLifecycle,
            AccountResource account)
        {
            var projectEditor = await Repository.Projects.CreateOrModify("Azure Cloud Service Sample", projectGroup, normalLifecycle);

            await projectEditor.SetLogo(SampleImageCache.DownloadImage("https://azurecomcdn.azureedge.net/cvt-9c42e10c78bceeb8622e49af8d0fe1a20cd9ca9f4983c398d0b356cf822d8844/images/shared/social/azure-icon-250x250.png"));

            var variableEditor = await projectEditor.Variables;

            if (variableEditor.Instance.Variables.All(v => v.Name != "UniqueName"))
            {
                variableEditor.AddOrUpdateVariableValue("UniqueName", Guid.NewGuid().ToString("N"));
            }
            variableEditor
            .AddOrUpdateVariableValue("CloudService", "AzureCloudService#{UniqueName}")
            .AddOrUpdateVariableValue("StorageAccount", storageAccountName)
            .AddOrUpdateVariableValue("Location", location);

            var processEditor = await projectEditor.DeploymentProcess;
            var process       = processEditor.Instance;

            process.Steps.Add(new DeploymentStepResource
            {
                Name      = "Create Azure Cloud Service",
                Condition = DeploymentStepCondition.Success,
                RequiresPackagesToBeAcquired = false,
                Actions =
                {
                    new DeploymentActionResource
                    {
                        ActionType = "Octopus.AzurePowerShell",
                        Name       = "Create Azure Cloud Service",
                        Properties =
                        {
                            { "Octopus.Action.Script.ScriptBody", "New-AzureService -ServiceName #{CloudService} -Location \"#{Location}\""   },
                            { "Octopus.Action.Azure.AccountId",   account.Id                                                                  }
                        }
                    }
                }
            });

            process.Steps.Add(new DeploymentStepResource
            {
                Name      = "Deploy Azure Cloud Service",
                Condition = DeploymentStepCondition.Success,
                RequiresPackagesToBeAcquired = true,
                Actions =
                {
                    new DeploymentActionResource
                    {
                        ActionType = "Octopus.AzureCloudService",
                        Name       = "Deploy Azure Cloud Service",
                        Properties =
                        {
                            { "Octopus.Action.Azure.AccountId",               account.Id                                            },
                            { "Octopus.Action.Azure.CloudServiceName",        "#{CloudService}"                                     },
                            { "Octopus.Action.Azure.StorageAccountName",      "#{StorageAccount}"                                   },
                            { "Octopus.Action.Azure.Slot",                    "Staging"                                             },
                            { "Octopus.Action.Azure.SwapIfPossible",          "False"                                               },
                            { "Octopus.Action.Azure.UseCurrentInstanceCount", "False"                                               },
                            { "Octopus.Action.Package.PackageId",             "Octopus.Sample.AzureCloudService"                    },
                            { "Octopus.Action.Package.FeedId",                "feeds-builtin"                                       }
                        }
                    }
                }
            });

            process.Steps.Add(new DeploymentStepResource
            {
                Name      = "Remove Azure Cloud Service",
                Condition = DeploymentStepCondition.Always,
                RequiresPackagesToBeAcquired = false,
                Actions =
                {
                    new DeploymentActionResource
                    {
                        ActionType = "Octopus.AzurePowerShell",
                        Name       = "Remove Azure Cloud Service",
                        Properties =
                        {
                            { "Octopus.Action.Script.ScriptBody", "Remove-AzureService -ServiceName #{CloudService} -Force"   },
                            { "Octopus.Action.Azure.AccountId",   account.Id                                                  }
                        }
                    }
                }
            });


            await projectEditor.Save();
        }
Exemplo n.º 25
0
        protected override void Execute()
        {
            if (!Repository.SupportsChannels())
            {
                throw new CommandException("Your Octopus server does not support channels, which was introduced in Octopus 3.2. Please upgrade your Octopus server to start using channels.");
            }
            if (string.IsNullOrWhiteSpace(projectName))
            {
                throw new CommandException("Please specify a project using the parameter: --project=ProjectXYZ");
            }
            if (string.IsNullOrWhiteSpace(channelName))
            {
                throw new CommandException("Please specify a channel name using the parameter: --channel=ChannelXYZ");
            }

            Log.Debug("Loading project {0}...", projectName);
            var project = Repository.Projects.FindByName(projectName);

            if (project == null)
            {
                throw new CouldNotFindException("project named", projectName);
            }

            LifecycleResource lifecycle = null;

            if (string.IsNullOrWhiteSpace(lifecycleName))
            {
                Log.Debug("No lifecycle specified. Going to inherit the project lifecycle...");
            }
            else
            {
                Log.Debug("Loading lifecycle {0}...", lifecycleName);
                lifecycle = Repository.Lifecycles.FindOne(l => string.Compare(l.Name, lifecycleName, StringComparison.OrdinalIgnoreCase) == 0);
                if (lifecycle == null)
                {
                    throw new CouldNotFindException("lifecycle named", lifecycleName);
                }
            }

            var channel = Repository.Projects.GetChannels(project)
                          .FindOne(Repository, ch => string.Equals(ch.Name, channelName, StringComparison.OrdinalIgnoreCase));

            if (channel == null)
            {
                channel = new ChannelResource
                {
                    ProjectId   = project.Id,
                    Name        = channelName,
                    IsDefault   = makeDefaultChannel ?? false,
                    Description = channelDescription ?? string.Empty,
                    LifecycleId = lifecycle?.Id, // Allow for the default lifeycle by propagating null
                    Rules       = new List <ChannelVersionRuleResource>(),
                };

                Log.Debug("Creating channel {0}", channelName);
                Repository.Channels.Create(channel);
                Log.Information("Channel {0} created", channelName);
                return;
            }

            if (!updateExisting)
            {
                throw new CommandException("This channel already exists. If you would like to update it, please use the parameter: --update-existing");
            }

            var updateRequired = false;

            if (channel.LifecycleId != lifecycle?.Id)
            {
                Log.Information("Updating this channel to {0}", lifecycle != null ? $"use lifecycle {lifecycle.Name} for promoting releases" : "inherit the project lifecycle for promoting releases");
                channel.LifecycleId = lifecycle?.Id;
                updateRequired      = true;
            }

            if (!channel.IsDefault && makeDefaultChannel == true)
            {
                Log.Information("Making this the default channel for {0}", project.Name);
                channel.IsDefault = makeDefaultChannel ?? channel.IsDefault;
                updateRequired    = true;
            }

            if (!string.IsNullOrWhiteSpace(channelDescription) && channel.Description != channelDescription)
            {
                Log.Information("Updating channel description to '{0}'", channelDescription);
                channel.Description = channelDescription ?? channel.Description;
                updateRequired      = true;
            }

            if (!updateRequired)
            {
                Log.Information("The channel already looks exactly the way it should, no need to update it.");
                return;
            }

            Log.Debug("Updating channel {0}", channelName);
            Repository.Channels.Modify(channel);
            Log.Information("Channel {0} updated", channelName);
        }
        private async Task <ProjectResource> BuildClientProject(ProjectGroupResource projectGroup, LifecycleResource normalLifecycle, LibraryVariableSetResource[] libraryVariableSets, Func <string, TagResource> getTag)
        {
            Log.Information("Setting up client project...");
            var clientProjectEditor = await Repository.Projects.CreateOrModify("Truck Tracker Client", projectGroup, normalLifecycle);

            await clientProjectEditor.SetLogo(SampleImageCache.DownloadImage("http://b2bimg.bridgat.com/files/GPS_Camera_TrackerGPS_Camera_Tracking.jpg", "GPS_Camera_TrackerGPS_Camera_Tracking.jpg"));

            clientProjectEditor.IncludingLibraryVariableSets(libraryVariableSets)
            .Customize(p => p.TenantedDeploymentMode = TenantedDeploymentMode.Tenanted);

            var channel = await clientProjectEditor.Channels.CreateOrModify("1.x Normal", "The channel for stable releases that will be deployed to our production trucks.");

            channel.SetAsDefaultChannel()
            .AddOrUpdateTenantTags(getTag("Canary"), getTag("Stable"));

            await clientProjectEditor.Channels.Delete("Default");

            var deploymentProcess = await clientProjectEditor.DeploymentProcess;

            deploymentProcess.AddOrUpdateStep("Deploy Application")
            .TargetingRoles("truck")
            .AddOrUpdateScriptAction("Deploy Application", new InlineScriptActionFromFileInAssembly("TrucksSample.Client.Deploy.fsx"), ScriptTarget.Target);

            var machineFilter = new MachineFilterResource();

            machineFilter.EventGroups.Add("MachineAvailableForDeployment");
            await clientProjectEditor.Triggers.CreateOrModify("Auto-Deploy to trucks when available",
                                                              machineFilter,
                                                              new AutoDeployActionResource());

            await clientProjectEditor.Save();

            return(clientProjectEditor.Instance);
        }
Exemplo n.º 27
0
        public async Task<ProjectEditor> CreateOrModify(string name, ProjectGroupResource projectGroup, LifecycleResource lifecycle, string description)
        {
            var existing = await repository.FindByName(name).ConfigureAwait(false);

            if (existing == null)
            {
                Instance = await repository.Create(new ProjectResource
                {
                    Name = name,
                    ProjectGroupId = projectGroup.Id,
                    LifecycleId = lifecycle.Id,
                    Description = description
                }).ConfigureAwait(false);
            }
            else
            {
                existing.Name = name;
                existing.ProjectGroupId = projectGroup.Id;
                existing.LifecycleId = lifecycle.Id;
                existing.Description = description;

                Instance = await repository.Modify(existing).ConfigureAwait(false);
            }

            return this;
        }
Exemplo n.º 28
0
        /// <summary>
        /// Gathers a list of Environments of a Lifecycle
        /// </summary>
        /// <param name="octRepository">The repository to call against.</param>
        /// <param name="lifecycle">Lifecycle to gather from.</param>
        /// <param name="phaseName">Phase name to gather from</param>
        /// <returns>Enumerable of EnvironmentResources</returns>
        public static IEnumerable <EnvironmentResource> GetLifeCyclePhaseEnvironments(OctopusRepository octRepository, LifecycleResource lifecycle, string phaseName)
        {
            var environmentList = new List <EnvironmentResource>();
            var lifecylePhase   = LifecycleHelper.GetPhaseByName(lifecycle, phaseName);

            return(GetPhaseEnvironments(octRepository, lifecylePhase));
        }
Exemplo n.º 29
0
        public ProjectEditor CreateOrModify(string name, ProjectGroupResource projectGroup, LifecycleResource lifecycle)
        {
            var existing = repository.FindByName(name);

            if (existing == null)
            {
                Instance = repository.Create(new ProjectResource
                {
                    Name           = name,
                    ProjectGroupId = projectGroup.Id,
                    LifecycleId    = lifecycle.Id,
                });
            }
            else
            {
                existing.Name           = name;
                existing.ProjectGroupId = projectGroup.Id;
                existing.LifecycleId    = lifecycle.Id;

                Instance = repository.Modify(existing);
            }

            return(this);
        }
Exemplo n.º 30
0
 private static void ConfigureLifecycle(LifecycleResource lifecycle)
 {
     //var lifecycle = _repository.Lifecycles.FindByName(lifecycleName);
 }