Esempio n. 1
0
        public void Setup()
        {
            mockRepo = Substitute.For <IOctopusAsyncRepository>();

            repoForSpaceScopedResource  = new TestSpaceResourceAsyncRepository(mockRepo, "", async repo => await Task.FromResult(""));
            repoForMixedScopedResource  = new TestMixedResourceAsyncRepository(mockRepo, "");
            repoForSystemScopedResource = new TestSystemResourceAsyncRepository(mockRepo, "", async repo => await Task.FromResult(""));

            mockRepo.LoadRootDocument().Returns(GetRootResource());

            someSpace = new SpaceResource
            {
                Id        = "Spaces-1",
                Name      = "Some Space",
                IsDefault = false
            };

            otherSpace = new SpaceResource()
            {
                Id        = "Spaces-2",
                Name      = "Another space",
                IsDefault = false
            };

            mockRepo.Scope.Returns(RepositoryScope.ForSpace(someSpace));

            RootResource GetRootResource()
            {
                return(new RootResource
                {
                    ApiVersion = "3.0.0",
                    Version = "2099.0.0"
                });
            }
        }
Esempio n. 2
0
        public ActionResult <OctoRelease> CreateReleaseResult()
        {
            CreateClient();
            var relResult = new ActionResult <OctoRelease>();

            var space      = _client.ForSystem().Spaces.FindByName(_inputs.SpaceName);
            var newRelease = BuildNewRelease();

            relResult.Error = newRelease.Error;

            if (newRelease.Result == null)
            {
                return(relResult);
            }

            var repo = new OctopusRepository(_client, RepositoryScope.ForSpace(space));

            try
            {
                var relResource = repo.Releases.Create(newRelease.Result);
                relResult.Result = relResource.ToOctoRelease();
            }
            catch (Exception ex)
            {
                relResult.Error.ErrorCount++;
                relResult.Error.ParseException(ex);
            }

            return(relResult);
        }
Esempio n. 3
0
        public ActionResult <OctoDeployment> CreateDeploymentResult()
        {
            CreateClient();
            var depResult = new ActionResult <OctoDeployment>();

            var space     = _client.ForSystem().Spaces.FindByName(_inputs.SpaceName);
            var newDeploy = BuildNewDeployment();

            depResult.Error = newDeploy.Error;

            if (depResult.HasErrors())
            {
                return(depResult);
            }

            var repo = new OctopusRepository(_client, RepositoryScope.ForSpace(space));

            try
            {
                var depResource = repo.Deployments.Create(newDeploy.Result);
                depResult.Result = depResource.ToOctoDeployment();
            }
            catch (Exception ex)
            {
                depResult.Error.ParseException(ex);
            }

            return(depResult);
        }
Esempio n. 4
0
        public async Task SpaceScoped_SingleSpaceContextShouldEnrichSpaceId(string spaceId)
        {
            var client = SetupAsyncClient();
            await client.Create(Arg.Any <string>(), Arg.Do <ProjectGroupResource>(t =>
            {
                t.SpaceId.Should().Be(spaceId);
            }));

            var repo = new ProjectGroupRepository(new OctopusAsyncRepository(client, RepositoryScope.ForSpace(CreateSpaceResource(spaceId))));
            var _    = await repo.Create(new ProjectGroupResource { Name = "Test" }).ConfigureAwait(false);
        }
Esempio n. 5
0
 static IEnumerable <TestCaseData> TestCases()
 {
     return(new[]
     {
         new TestCaseData(RepositoryScope.ForSystem()),
         new TestCaseData(RepositoryScope.ForSpace(new SpaceResource {
             Id = "Spaces-1", Links = new LinkCollection {
                 { "SpaceHome", String.Empty }
             }
         }))
     });
 }
Esempio n. 6
0
        public async Task MixedScoped_SingleSpaceContextShouldEnrichSpaceId(string spaceId)
        {
            var client = SetupAsyncClient();
            await client.Create(Arg.Any <string>(), Arg.Do <TeamResource>(t =>
            {
                t.SpaceId.Should().Be(spaceId);
            })).ConfigureAwait(false);

            var teamRepo = new TeamsRepository(new OctopusAsyncRepository(client, RepositoryScope.ForSpace(CreateSpaceResource(spaceId))));
            var created  = await teamRepo.Create(new TeamResource()
            {
                Name = "Test"
            }).ConfigureAwait(false);
        }
Esempio n. 7
0
        public void Setup()
        {
            mockRepo = Substitute.For <IOctopusAsyncRepository>();

            repoForSpaceScopedResource  = new TestSpaceResourceAsyncRepository(mockRepo, "", async repo => await Task.FromResult(""));
            repoForMixedScopedResource  = new TestMixedResourceAsyncRepository(mockRepo, "");
            repoForSystemScopedResource = new TestSystemResourceAsyncRepository(mockRepo, "", async repo => await Task.FromResult(""));

            someSpace = new SpaceResource
            {
                Id        = "Spaces-1",
                Name      = "Some Space",
                IsDefault = false
            };

            otherSpace = new SpaceResource()
            {
                Id        = "Spaces-2",
                Name      = "Another space",
                IsDefault = false
            };

            mockRepo.Scope.Returns(RepositoryScope.ForSpace(someSpace));
        }
Esempio n. 8
0
        public async Task Execute(string[] commandLineArguments)
        {
            var remainingArguments = Options.Parse(commandLineArguments);

            if (printHelp)
            {
                this.GetHelp(Console.Out, commandLineArguments);

                return;
            }

            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/. " +
                                           $"The Octopus Server URL can also be set in the {ServerUrlEnvVar} environment variable.");
            }

            if (!string.IsNullOrWhiteSpace(ApiKey) && !string.IsNullOrWhiteSpace(Username))
            {
                throw new CommandException("Please provide an API Key OR a username and password, not both. " +
                                           "These values may have been passed in as command line arguments, or may have been set in the " +
                                           $"{ApiKeyEnvVar} and {UsernameEnvVar} environment variables.");
            }

            if (string.IsNullOrWhiteSpace(ApiKey) && string.IsNullOrWhiteSpace(Username))
            {
                throw new CommandException("Please specify your API key using --apiKey=ABCDEF123456789 OR a username and password. " +
                                           $"The API key can also be set in the {ApiKeyEnvVar} environment variable, " +
                                           $"while the username and password can be set in the {UsernameEnvVar} and {PasswordEnvVar} " +
                                           "environment variables respectively. Learn more at: https://github.com/OctopusDeploy/Octopus-Tools");
            }

            var endpoint = string.IsNullOrWhiteSpace(ApiKey)
                ? new OctopusServerEndpoint(ServerBaseUrl)
                : new OctopusServerEndpoint(ServerBaseUrl, ApiKey);

#if HTTP_CLIENT_SUPPORTS_SSL_OPTIONS
            clientOptions.IgnoreSslErrors = ignoreSslErrors;
#else
            ServicePointManager.ServerCertificateValidationCallback = ServerCertificateValidationCallback;
#endif

            commandOutputProvider.PrintMessages = OutputFormat == OutputFormat.Default || enableDebugging;
            commandOutputProvider.PrintHeader();

            var client = await clientFactory.CreateAsyncClient(endpoint, clientOptions).ConfigureAwait(false);

            var serverHasSpaces = await client.ForSystem().HasLink("Spaces").ConfigureAwait(false);

            if (!string.IsNullOrEmpty(spaceName))
            {
                if (!serverHasSpaces)
                {
                    throw new CommandException($"The server {endpoint.OctopusServer} has no spaces. Try invoking the Octo tool without specifying the space name as an argument");
                }

                commandOutputProvider.Debug("Finding space: {Space:l}", spaceName);
                var space = await client.ForSystem().Spaces.FindByName(spaceName).ConfigureAwait(false);

                if (space == null)
                {
                    throw new CommandException($"Cannot find the space with name {spaceName}");
                }

                Repository = repositoryFactory.CreateRepository(client, RepositoryScope.ForSpace(space));
                commandOutputProvider.Debug("Space name specified, process is now running in the context of space: {space:l}", spaceName);
            }
            else
            {
                Repository = repositoryFactory.CreateRepository(client);

                if (!serverHasSpaces)
                {
                    commandOutputProvider.Debug("Process will run in backwards compatible mode for older versions of Octopus Server");
                }
                else
                {
                    var defaultSpace = await client.ForSystem().Spaces.FindOne(space => space.IsDefault)
                                       .ConfigureAwait(false);

                    if (defaultSpace == null)
                    {
                        throw new CommandException("Octopus Server does not have a default space enabled, hence you need to specify the space name as an argument");
                    }

                    commandOutputProvider.Debug("Space name unspecified, process will run in the default space context");
                }
            }

            RepositoryCommonQueries = new OctopusRepositoryCommonQueries(Repository, commandOutputProvider);

            if (enableDebugging)
            {
                Repository.Client.SendingOctopusRequest += request => commandOutputProvider.Debug("{Method:l} {Uri:l}", request.Method, request.Uri);
            }

            commandOutputProvider.Debug("Handshaking with Octopus Server: {Url:l}", ServerBaseUrl);

            var root = await Repository.LoadRootDocument().ConfigureAwait(false);

            commandOutputProvider.Debug("Handshake successful. Octopus version: {Version:l}; API version: {ApiVersion:l}", root.Version, root.ApiVersion);

            if (!string.IsNullOrWhiteSpace(Username))
            {
                await Repository.Users.SignIn(Username, Password).ConfigureAwait(false);
            }

            var user = await Repository.Users.GetCurrent().ConfigureAwait(false);

            if (user != null)
            {
                commandOutputProvider.Debug("Authenticated as: {Name:l} <{EmailAddress:l}> {IsService:l}", user.DisplayName, user.EmailAddress, user.IsService ? "(a service account)" : "");
            }

            await ValidateParameters().ConfigureAwait(false);
            await Execute().ConfigureAwait(false);
        }
Esempio n. 9
0
 public static void SetupScopeForSpace(this IOctopusAsyncRepository repo, string space)
 {
     repo.Scope.Returns(RepositoryScope.ForSpace(new SpaceResource {
         Id = space, IsDefault = false
     }));
 }
Esempio n. 10
0
        public override async Task Execute(string[] commandLineArguments)
        {
            var remainingArguments = Options.Parse(commandLineArguments);

            if (printHelp)
            {
                GetHelp(Console.Out, commandLineArguments);

                return;
            }

            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/. " +
                                           $"The Octopus Server URL can also be set in the {ServerUrlEnvVar} environment variable.");
            }

            if (!string.IsNullOrWhiteSpace(ApiKey) && !string.IsNullOrWhiteSpace(Username))
            {
                throw new CommandException("Please provide an API Key OR a username and password, not both. " +
                                           "These values may have been passed in as command line arguments, or may have been set in the " +
                                           $"{ApiKeyEnvVar} and {UsernameEnvVar} environment variables.");
            }

            if (string.IsNullOrWhiteSpace(ApiKey) && string.IsNullOrWhiteSpace(Username))
            {
                throw new CommandException("Please specify your API key using --apiKey=ABCDEF123456789 OR a username and password. " +
                                           $"The API key can also be set in the {ApiKeyEnvVar} environment variable, " +
                                           $"while the username and password can be set in the {UsernameEnvVar} and {PasswordEnvVar} " +
                                           "environment variables respectively. Learn more at: https://github.com/OctopusDeploy/Octopus-Tools");
            }

            var endpoint = string.IsNullOrWhiteSpace(ApiKey)
                ? new OctopusServerEndpoint(ServerBaseUrl)
                : new OctopusServerEndpoint(ServerBaseUrl, ApiKey);

#if NETFRAMEWORK
            /*
             * There may be a delay between the completion of a large file upload and when Octopus responds
             * to finish the HTTP connection. This delay can be several minutes. During this time, no traffic is
             * sent, and some networking infrastructure will close the connection. For example, Azure VMs will
             * close idle connections after 4 minutes, and AWS VMs will close them after 350 seconds. The
             * TCP keepalive option will ensure that the connection is not idle at the end of the file upload.
             *
             * This is the bug that explains why this doesn't work with .NET Core:
             * https://github.com/dotnet/corefx/issues/26013
             */
            if (keepAlive > 0)
            {
                ServicePointManager.FindServicePoint(new Uri(ServerBaseUrl)).SetTcpKeepAlive(true, keepAlive, keepAlive);
            }
#endif

#if HTTP_CLIENT_SUPPORTS_SSL_OPTIONS
            clientOptions.IgnoreSslErrors = ignoreSslErrors;
#else
            ServicePointManager.ServerCertificateValidationCallback = ServerCertificateValidationCallback;
#endif

            commandOutputProvider.PrintMessages = OutputFormat == OutputFormat.Default || enableDebugging;
            CliSerilogLogProvider.PrintMessages = commandOutputProvider.PrintMessages;
            commandOutputProvider.PrintHeader();

            var client = await clientFactory.CreateAsyncClient(endpoint, clientOptions).ConfigureAwait(false);

            if (!string.IsNullOrWhiteSpace(Username))
            {
                await client.Repository.Users.SignIn(Username, Password).ConfigureAwait(false);
            }

            var serverHasSpaces = await client.ForSystem().HasLink("Spaces").ConfigureAwait(false);

            if (!string.IsNullOrEmpty(spaceNameOrId))
            {
                if (!serverHasSpaces)
                {
                    throw new CommandException($"The server {endpoint.OctopusServer} has no spaces. Try invoking {AssemblyExtensions.GetExecutableName()} without specifying the space name as an argument");
                }

                var space = await client.ForSystem().Spaces.FindByNameOrIdOrFail(spaceNameOrId).ConfigureAwait(false);

                Repository = repositoryFactory.CreateRepository(client, RepositoryScope.ForSpace(space));
                commandOutputProvider.Debug("Space name specified, process is now running in the context of space: {space:l}", space.Name);
            }
            else
            {
                Repository = repositoryFactory.CreateRepository(client);

                if (!serverHasSpaces)
                {
                    commandOutputProvider.Debug("Process will run in backwards compatible mode for older versions of Octopus Server");
                }
                else
                {
                    var defaultSpace = await client.ForSystem()
                                       .Spaces.FindOne(space => space.IsDefault)
                                       .ConfigureAwait(false);

                    if (defaultSpace == null)
                    {
                        throw new CommandException("Octopus Server does not have a default space enabled, hence you need to specify the space name as an argument");
                    }

                    commandOutputProvider.Debug("Space name unspecified, process will run in the default space context");
                }
            }

            RepositoryCommonQueries = new OctopusRepositoryCommonQueries(Repository, commandOutputProvider);

            if (enableDebugging)
            {
                Repository.Client.SendingOctopusRequest += request => commandOutputProvider.Debug("{Method:l} {Uri:l}", request.Method, request.Uri);
            }

            commandOutputProvider.Debug("Handshaking with Octopus Server: {Url:l}", ServerBaseUrl);

            var root = await Repository.LoadRootDocument().ConfigureAwait(false);

            commandOutputProvider.Debug("Handshake successful. Octopus version: {Version:l}; API version: {ApiVersion:l}", root.Version, root.ApiVersion);

            var user = await Repository.Users.GetCurrent().ConfigureAwait(false);

            if (user != null)
            {
                if (string.IsNullOrEmpty(user.EmailAddress))
                {
                    commandOutputProvider.Debug("Authenticated as: {Name:l} {IsService:l}", user.DisplayName, user.IsService ? "(a service account)" : "");
                }
                else
                {
                    commandOutputProvider.Debug("Authenticated as: {Name:l} <{EmailAddress:l}> {IsService:l}", user.DisplayName, user.EmailAddress, user.IsService ? "(a service account)" : "");
                }
            }

            await ValidateParameters().ConfigureAwait(false);
            await Execute().ConfigureAwait(false);
        }