Exemplo n.º 1
0
        public void WaitForDeploymentsToFinish(IOctopusSession session, IEnumerable<string> linksToDeploymentTasks, TimeSpan timeout, TimeSpan deploymentStatusCheckSleepCycle)
        {
            IDictionary<string, Task> tasks;
            var stopwatch = Stopwatch.StartNew();
            do
            {
                tasks = linksToDeploymentTasks.ToDictionary(link => link, link => session.Get<Task>(link));
                var allTasksFinished = tasks.Values.All(task => task.IsFinished);
                if (allTasksFinished) break;

                EnsureDeploymentIsNotTakingLongerThanExpected(stopwatch.Elapsed, timeout);

                log.Debug(String.Format("Deployment not yet finished. It's taken {0} so far.", stopwatch.Elapsed));
                Thread.Sleep(deploymentStatusCheckSleepCycle);
            } while (true);

            var failedTasks = tasks.Values.Where(task => !task.FinishedSuccessfully);
            if (failedTasks.Any())
            {
                var message = "{0} of the deployment tasks has failed. Please check Octopus web site for more details. Failed tasks: {1}";
                var taskIds = failedTasks.Aggregate("", (accumulator, task) => accumulator + task.Id + ", ");
                throw new CommandException(String.Format(message, failedTasks.Count(), taskIds));
            }

            log.Debug("Deployment has finished succeessfully");
        }
Exemplo n.º 2
0
    public static IList <DeploymentEnvironment> FindEnvironments(this IOctopusSession session, ICollection <string> environmentNames)
    {
        if (environmentNames == null || !environmentNames.Any())
        {
            return(new List <DeploymentEnvironment>());
        }

        var list         = new List <DeploymentEnvironment>();
        var environments = session.List <DeploymentEnvironment>(session.RootDocument.Link("Environments"));

        foreach (var environmentName in environmentNames)
        {
            if (string.IsNullOrWhiteSpace(environmentName))
            {
                continue;
            }

            var environment = environments.FirstOrDefault(x => string.Equals(x.Name, environmentName, StringComparison.InvariantCultureIgnoreCase));
            if (environment == null)
            {
                throw new ArgumentException(string.Format("An environment named '{0}' could not be found.", environmentName));
            }

            list.Add(environment);
        }

        return(list);
    }
        public void WaitForDeploymentsToFinish(IOctopusSession session, IEnumerable <string> linksToDeploymentTasks, TimeSpan timeout, TimeSpan deploymentStatusCheckSleepCycle)
        {
            IDictionary <string, Task> tasks;
            var stopwatch = Stopwatch.StartNew();

            do
            {
                tasks = linksToDeploymentTasks.ToDictionary(link => link, link => session.Get <Task>(link));
                var allTasksFinished = tasks.Values.All(task => task.IsFinished);
                if (allTasksFinished)
                {
                    break;
                }

                EnsureDeploymentIsNotTakingLongerThanExpected(stopwatch.Elapsed, timeout);

                log.Debug(String.Format("Deployment not yet finished. It's taken {0} so far.", stopwatch.Elapsed));
                Thread.Sleep(deploymentStatusCheckSleepCycle);
            } while (true);

            var failedTasks = tasks.Values.Where(task => !task.FinishedSuccessfully);

            if (failedTasks.Any())
            {
                var message = "{0} of the deployment tasks has failed. Please check Octopus web site for more details. Failed tasks: {1}";
                var taskIds = failedTasks.Aggregate("", (accumulator, task) => accumulator + task.Id + ", ");
                throw new CommandException(String.Format(message, failedTasks.Count(), taskIds));
            }

            log.Debug("Deployment has finished succeessfully");
        }
 public CreateReleaseCommand(IOctopusSession session, ILog log, IDeploymentWatcher deploymentWatcher)
     : base(session, log)
 {
     this.deploymentWatcher = deploymentWatcher;
     DeployToEnvironmentNames = new List<string>();
     DeploymentStatusCheckSleepCycle = TimeSpan.FromSeconds(10);
     DeploymentTimeout = TimeSpan.FromMinutes(4);
 }
    public static Deployment DeployRelease(this IOctopusSession session, Release release, DeploymentEnvironment environment, bool forceRedeploymentOfExistingPackages = false)
    {
        var deployment = new Deployment();

        deployment.EnvironmentId     = environment.Id;
        deployment.ReleaseId         = release.Id;
        deployment.ForceRedeployment = forceRedeploymentOfExistingPackages;

        return(session.Create(release.Link("Deployments"), deployment));
    }
        public void SetUp()
        {
            configFile     = Path.GetTempFileName();
            sessionFactory = Substitute.For <IOctopusSessionFactory>();
            command        = new TestCommand(sessionFactory, Substitute.For <ILog>());

            session = Substitute.For <IOctopusSession>();
            sessionFactory.OpenSession(Arg.Any <Uri>(), Arg.Any <NetworkCredential>(), Arg.Any <string>(), Arg.Any <bool>()).Returns(session);
            session.RootDocument.Returns(new RootDocument());
        }
        public void SetUp()
        {
            configFile = Path.GetTempFileName();
            sessionFactory = Substitute.For<IOctopusSessionFactory>();
            command = new TestCommand(sessionFactory, Substitute.For<ILog>());

            session = Substitute.For<IOctopusSession>();
            sessionFactory.OpenSession(Arg.Any<Uri>(), Arg.Any<NetworkCredential>(), Arg.Any<string>(), Arg.Any<bool>()).Returns(session);
            session.RootDocument.Returns(new RootDocument());
        }
Exemplo n.º 8
0
    public static Release CreateRelease(this IOctopusSession session, Project project, IList <SelectedPackage> latestVersions, string version, string releaseNotes)
    {
        var release = new Release();

        release.Assembled        = DateTimeOffset.UtcNow;
        release.AssembledBy      = Environment.UserName;
        release.Version          = version;
        release.SelectedPackages = latestVersions.ToArray();
        release.ReleaseNotes     = releaseNotes ?? string.Empty;

        return(session.Create(project.Link("Releases"), release));
    }
Exemplo n.º 9
0
    public static Release GetRelease(this IOctopusSession session, Project project, string version)
    {
        var releases = session.List <Release>(project.Link("Releases"));

        var release = releases.FirstOrDefault(x => string.Equals(x.Version, version, StringComparison.InvariantCultureIgnoreCase));

        if (release == null)
        {
            throw new ArgumentException(string.Format("A release named '{0}' could not be found.", version));
        }

        return(release);
    }
Exemplo n.º 10
0
    public static Project GetProject(this IOctopusSession session, string projectName)
    {
        var projects = session.List <Project>(session.RootDocument.Link("Projects"));

        var project = projects.FirstOrDefault(x => string.Equals(x.Name, projectName, StringComparison.InvariantCultureIgnoreCase));

        if (project == null)
        {
            throw new ArgumentException(string.Format("A project named '{0}' could not be found.", projectName));
        }

        return(project);
    }
Exemplo n.º 11
0
    public static IEnumerable <string> GetDeployments(this IOctopusSession session, Release release, IEnumerable <DeploymentEnvironment> environments, bool force, bool forceDownloadOfPackages, ILog log)
    {
        var linksToDeploymentTasks = new List <string>();

        foreach (var environment in environments)
        {
            var deployment = session.DeployRelease(release, environment, force, forceDownloadOfPackages);
            var linkToTask = deployment.Link("Task");
            linksToDeploymentTasks.Add(linkToTask);

            log.InfoFormat("Successfully scheduled release {0} for deployment to environment {1}", release.Version, environment.Name);
        }
        return(linksToDeploymentTasks);
    }
Exemplo n.º 12
0
    public static SelectedPackage GetLatestPackageForStep(this IOctopusSession session, Step step)
    {
        var versions = session.List <PackageVersion>(step.Link("AvailablePackageVersions"));

        var latest = versions.FirstOrDefault();

        if (latest == null)
        {
            throw new Exception(string.Format("There are no available packages named '{0}'.", step.NuGetPackageId));
        }

        return(new SelectedPackage {
            StepId = step.Id, NuGetPackageVersion = latest.Version
        });
    }
Exemplo n.º 13
0
    public static SelectedPackage GetPackageForStep(this IOctopusSession session, Step step, string version)
    {
        var versions = session.List <PackageVersion>(step.Link("AvailablePackageVersions"));

        var latest = versions.Where(s => (s.Version == version)).First();

        if (latest == null)
        {
            throw new Exception("There are no available packages named '{0}'");
        }

        return(new SelectedPackage {
            StepId = step.Id, NuGetPackageVersion = latest.Version
        });
    }
        IEnumerable<Task> WaitUntilTasksFinish(IOctopusSession session, IList<string> linksToDeploymentTasks, TimeSpan timeout, TimeSpan deploymentStatusCheckSleepCycle)
        {
            var stopwatch = Stopwatch.StartNew();

            while (true)
            {
                var tasks = FetchTasks(session, linksToDeploymentTasks);

                var allFinished = tasks.All(task => task.IsFinished);
                if (allFinished)
                    return tasks;

                EnsureDeploymentIsNotTakingLongerThanExpected(stopwatch.Elapsed, timeout);

                log.DebugFormat("Deployment has not yet finished. Time taken: {0}", stopwatch.Elapsed.Friendly());

                Thread.Sleep(deploymentStatusCheckSleepCycle);
            }
        }
        public void WaitForDeploymentsToFinish(IOctopusSession session, IList<string> linksToDeploymentTasks, TimeSpan timeout, TimeSpan deploymentStatusCheckSleepCycle)
        {
            var tasks = WaitUntilTasksFinish(session, linksToDeploymentTasks, timeout, deploymentStatusCheckSleepCycle);

            var failedTasks = tasks.Where(task => !task.FinishedSuccessfully).ToList();
            if (failedTasks.Any())
            {
                var message = new StringBuilder();
                foreach (var task in failedTasks)
                {
                    message.AppendFormat("The task: '{0}' failed with the error: {1}", task.Description, task.ErrorMessage).AppendLine();
                    message.AppendFormat("Please see the deployment page for more details: {0}", session.QualifyWebLink(task.Link("Web"))).AppendLine();
                }

                throw new CommandException(message.ToString());
            }

            log.Debug("Deployment finished successfully!");
        }
Exemplo n.º 16
0
    public static Release GetRelease(this IOctopusSession session, Project project, string version)
    {
        var releases = session.List <Release>(project.Link("Releases"));

        Release release;

        if (version.ToLower() == "latest")
        {
            release = releases.OrderByDescending(r => SemanticVersion.Parse(r.Version)).FirstOrDefault();
        }
        else
        {
            release = releases.FirstOrDefault(x => string.Equals(x.Version, version, StringComparison.InvariantCultureIgnoreCase));
        }
        if (release == null)
        {
            throw new ArgumentException(string.Format("A release named '{0}' for project '{1}' could not be found.", version, project.Name));
        }
        return(release);
    }
Exemplo n.º 17
0
        public void WaitForDeploymentsToFinish(IOctopusSession session, IList <string> linksToDeploymentTasks, TimeSpan timeout, TimeSpan deploymentStatusCheckSleepCycle)
        {
            var tasks = WaitUntilTasksFinish(session, linksToDeploymentTasks, timeout, deploymentStatusCheckSleepCycle);

            var failedTasks = tasks.Where(task => !task.FinishedSuccessfully).ToList();

            if (failedTasks.Any())
            {
                var message = new StringBuilder();
                foreach (var task in failedTasks)
                {
                    message.AppendFormat("The task: '{0}' failed with the error: {1}", task.Description, task.ErrorMessage).AppendLine();
                    message.AppendFormat("Please see the deployment page for more details: {0}", session.QualifyWebLink(task.Link("Web"))).AppendLine();
                }

                throw new CommandException(message.ToString());
            }

            log.Debug("Deployment finished successfully!");
        }
Exemplo n.º 18
0
        IEnumerable <Task> WaitUntilTasksFinish(IOctopusSession session, IList <string> linksToDeploymentTasks, TimeSpan timeout, TimeSpan deploymentStatusCheckSleepCycle)
        {
            var stopwatch = Stopwatch.StartNew();

            while (true)
            {
                var tasks = FetchTasks(session, linksToDeploymentTasks);

                var allFinished = tasks.All(task => task.IsFinished);
                if (allFinished)
                {
                    return(tasks);
                }

                EnsureDeploymentIsNotTakingLongerThanExpected(stopwatch.Elapsed, timeout);

                log.DebugFormat("Deployment has not yet finished. Time taken: {0}", stopwatch.Elapsed.Friendly());

                Thread.Sleep(deploymentStatusCheckSleepCycle);
            }
        }
Exemplo n.º 19
0
 public static IList <Project> ListProjects(this IOctopusSession session)
 {
     return(session.List <Project>(session.RootDocument.Link("Projects")));
 }
Exemplo n.º 20
0
 protected ApiCommand(IOctopusSession client, ILog log)
 {
     this.log = log;
     this.client = client;
 }
Exemplo n.º 21
0
 public static IList <DeploymentEnvironment> ListEnvironments(this IOctopusSession session)
 {
     return(session.List <DeploymentEnvironment>(session.RootDocument.Link("Environments")));
 }
Exemplo n.º 22
0
 public static IList <Release> GetReleases(this IOctopusSession session, Project project, int skip, int take)
 {
     return(session.List <Release>(project.Link("Releases"), new QueryString {
         { "skip", skip }, { "take", take }
     }));
 }
 public ListEnvironmentsCommand(IOctopusSession session, ILog log)
     : base(session, log)
 {
 }
Exemplo n.º 24
0
        public void Execute(string[] commandLineArguments)
        {
            SetOptions(options);

            var remainingArguments = options.Parse(commandLineArguments);
            if (remainingArguments.Count > 0)
                throw new CommandException("Unrecognized command arguments: " + string.Join(", ", remainingArguments));

            if (string.IsNullOrWhiteSpace(serverBaseUrl))
                throw new CommandException("Please specify the Octopus Server URL using --server=http://your-server/");

            if (string.IsNullOrWhiteSpace(apiKey))
                throw new CommandException("Please specify your API key using --apiKey=ABCDEF123456789. Learn more at: https://github.com/OctopusDeploy/Octopus-Tools");

            var credentials = ParseCredentials(user, pass);

            Uri serverBaseUri;
            if (!Uri.TryCreate(serverBaseUrl, UriKind.Absolute, out serverBaseUri))
                throw new CommandException("Invalid URI format. Please specify an Octopus Server URL using --server=http://your-server/");
            if (serverBaseUri.Scheme != "http" && serverBaseUri.Scheme != "https")
                throw new CommandException("Invalid URI format, the URI should start with 'http' or 'https'. Please specify an Octopus Server URL using --server=http://your-server/");

            session = client.OpenSession(serverBaseUri, credentials, apiKey, enableDebugging);

            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) =>
            {
                if (errors == SslPolicyErrors.None)
                {
                    return true;
                }

                var certificate2 = (X509Certificate2)certificate;
                var warning = "The following certificate errors were encountered when establishing the HTTPS connection to the server: " + errors + Environment.NewLine +
                              "Certificate subject name: " + certificate2.SubjectName.Name + Environment.NewLine +
                              "Certificate thumbprint:   " + ((X509Certificate2)certificate).Thumbprint;

                if (ignoreSslErrors)
                {
                    log.Warn(warning);
                    log.Warn("Because --ignoreSslErrors was set, this will be ignored.");
                    return true;
                }

                log.Error(warning);
                return false;
            };

            log.Debug("Handshaking with Octopus server: " + serverBaseUrl);
            var root = session.RootDocument;
            log.Debug("Handshake successful. Octopus version: " + root.Version + "; API version: " + root.ApiVersion);

            Execute();
        }
Exemplo n.º 25
0
 public static IList <Step> FindStepsForProject(this IOctopusSession session, Project project)
 {
     return(session.List <Step>(project.Link("Steps")));
 }
Exemplo n.º 26
0
 public static IEnumerable <Deployment> GetMostRecentDeployments(this IOctopusSession session, Project project)
 {
     return(session.List <Deployment>(project.Link(("RecentDeployments"))));
 }
Exemplo n.º 27
0
 public DeploymentWatcher(IOctopusSession session, ILog log)
 {
     this.session = session;
     this.log = log;
 }
Exemplo n.º 28
0
 static IList <Task> FetchTasks(IOctopusSession session, IEnumerable <string> linksToDeploymentTasks)
 {
     return(linksToDeploymentTasks.Select(session.Get <Task>).ToList());
 }
 static IList<Task> FetchTasks(IOctopusSession session, IEnumerable<string> linksToDeploymentTasks)
 {
     return linksToDeploymentTasks.Select(session.Get<Task>).ToList();
 }
Exemplo n.º 30
0
        public void Execute(string[] commandLineArguments)
        {
            SetOptions(options);

            var remainingArguments = options.Parse(commandLineArguments);

            if (remainingArguments.Count > 0)
            {
                throw new CommandException("Unrecognized command arguments: " + string.Join(", ", remainingArguments));
            }

            if (string.IsNullOrWhiteSpace(serverBaseUrl))
            {
                throw new CommandException("Please specify the Octopus Server URL using --server=http://your-server/");
            }

            if (string.IsNullOrWhiteSpace(apiKey))
            {
                throw new CommandException("Please specify your API key using --apiKey=ABCDEF123456789. Learn more at: https://github.com/OctopusDeploy/Octopus-Tools");
            }

            var credentials = ParseCredentials(user, pass);

            Uri serverBaseUri;

            if (!Uri.TryCreate(serverBaseUrl, UriKind.Absolute, out serverBaseUri))
            {
                throw new CommandException("Invalid URI format. Please specify an Octopus Server URL using --server=http://your-server/");
            }
            if (serverBaseUri.Scheme != "http" && serverBaseUri.Scheme != "https")
            {
                throw new CommandException("Invalid URI format, the URI should start with 'http' or 'https'. Please specify an Octopus Server URL using --server=http://your-server/");
            }

            session = client.OpenSession(serverBaseUri, credentials, apiKey, enableDebugging);

            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) =>
            {
                if (errors == SslPolicyErrors.None)
                {
                    return(true);
                }

                var certificate2 = (X509Certificate2)certificate;
                var warning      = "The following certificate errors were encountered when establishing the HTTPS connection to the server: " + errors + Environment.NewLine +
                                   "Certificate subject name: " + certificate2.SubjectName.Name + Environment.NewLine +
                                   "Certificate thumbprint:   " + ((X509Certificate2)certificate).Thumbprint;

                if (ignoreSslErrors)
                {
                    log.Warn(warning);
                    log.Warn("Because --ignoreSslErrors was set, this will be ignored.");
                    return(true);
                }

                log.Error(warning);
                return(false);
            };

            log.Debug("Handshaking with Octopus server: " + serverBaseUrl);
            var root = session.RootDocument;

            log.Debug("Handshake successful. Octopus version: " + root.Version + "; API version: " + root.ApiVersion);

            Execute();
        }
 public DeployReleaseCommand(IOctopusSession session, ILog log)
     : base(session, log)
 {
     DeployToEnvironmentNames = new List<string>();
 }