Example #1
0
        public void Init()
        {
            _ps = Utilities.CreatePowerShell(CmdletName, typeof(GetMachine));

            var octoRepo = Utilities.AddOctopusRepo(_ps.Runspace.SessionStateProxy.PSVariable);

            var machine = new MachineResource {
                Name = "dbserver-01", Id = "Machines-1"
            };
            var machines = new List <MachineResource>
            {
                machine,
                new MachineResource {
                    Name = "dbserver-02", Id = "Machines-2"
                }
            };

            octoRepo.Setup(o => o.Machines.FindAll(null, null)).Returns(machines);
            octoRepo.Setup(o => o.Machines.FindByNames(new[] { "dbserver-01" }, null, null)).Returns(new List <MachineResource> {
                machine
            });
            octoRepo.Setup(o => o.Machines.FindByNames(new[] { "Gibberish" }, null, null)).Returns(new List <MachineResource>());

            octoRepo.Setup(o => o.Machines.Get("Machines-1")).Returns(machine);
            octoRepo.Setup(o => o.Machines.Get(It.Is((string s) => s != "Machines-1"))).Throws(new OctopusResourceNotFoundException("Not Found"));
        }
Example #2
0
        private void UploadTenantMappingForMachine(MachineResource machineResource, IEnumerable <Tenant> tenants, List <string> knownTenants)
        {
            var knownTenantIds   = GetTenantIdsByNames(knownTenants);
            var unknownTenantIds = machineResource.TenantIds.Except(knownTenantIds, _comparer).ToList();

            var tenantsForMachine = tenants
                                    .Where(x => x.Machines.Contains(machineResource.Name, _comparer))
                                    .Select(x => x.Name)
                                    .ToList();

            var tenantIds = GetTenantIdsByNames(tenantsForMachine)
                            .Concat(unknownTenantIds)
                            .ToList();

            if (tenantIds.Count == 0)
            {
                return;
            }

            Logger.Info($"Updating {machineResource.Name} with tenants:");
            OutputMappingChanges(GetTenantNamesByIds(machineResource.TenantIds.ToList()), GetTenantNamesByIds(tenantIds), GetTenantNamesByIds(unknownTenantIds));

            machineResource.TenantIds = new ReferenceCollection(tenantIds);
            _repository.Machines.Modify(machineResource);
        }
        void ApplyChanges(MachineResource machine, IEnumerable <EnvironmentResource> environment, MachinePolicyResource machinePolicy, IEnumerable <TenantResource> tenants)
        {
            machine.EnvironmentIds = new ReferenceCollection(environment.Select(e => e.Id).ToArray());
            machine.TenantIds      = new ReferenceCollection(tenants.Select(t => t.Id).ToArray());
            machine.TenantTags     = new ReferenceCollection(TenantTags);
            machine.Roles          = new ReferenceCollection(Roles);
            machine.Name           = MachineName;
            if (machinePolicy != null)
            {
                machine.MachinePolicyId = machinePolicy.Id;
            }

            if (CommunicationStyle == CommunicationStyle.TentaclePassive)
            {
                var listening = new ListeningTentacleEndpointResource();
                listening.Uri        = new Uri("https://" + TentacleHostname.ToLowerInvariant() + ":" + TentaclePort.ToString(CultureInfo.InvariantCulture) + "/").ToString();
                listening.Thumbprint = TentacleThumbprint;
                machine.Endpoint     = listening;
            }
            else if (CommunicationStyle == CommunicationStyle.TentacleActive)
            {
                var polling = new PollingTentacleEndpointResource();
                polling.Uri        = SubscriptionId.ToString();
                polling.Thumbprint = TentacleThumbprint;
                machine.Endpoint   = polling;
            }
        }
        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);
        }
Example #5
0
 void ApplyDeploymentTargetChanges(MachineResource machine, IEnumerable <EnvironmentResource> environment, IEnumerable <TenantResource> tenants)
 {
     machine.EnvironmentIds = new ReferenceCollection(environment.Select(e => e.Id).ToArray());
     machine.TenantIds      = new ReferenceCollection(tenants.Select(t => t.Id).ToArray());
     machine.TenantTags     = new ReferenceCollection(TenantTags);
     machine.Roles          = new ReferenceCollection(Roles);
     machine.TenantedDeploymentParticipation = TenantedDeploymentParticipation;
 }
Example #6
0
        public void CreateAndRemoveMachine()
        {
            #region MachineCreate

            var environmentId = TestUtilities.Repository.Environments.FindAll().FirstOrDefault().Id;

            var resource = new MachineResource()
            {
                Name     = TestResourceName,
                Endpoint = new OfflineDropEndpointResource()
                {
                    ApplicationsDirectory   = "SomePath",
                    DropFolderPath          = "SomePath",
                    OctopusWorkingDirectory = "SomePath"
                },
                EnvironmentIds = ReferenceCollection.One(environmentId),
                Roles          = ReferenceCollection.One("WebServer"),
            };

            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 <MachineResource>().FirstOrDefault();

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

            #region MachineDelete
            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
        }
Example #7
0
        private MachineResource CreateMachine(int prefix)
        {
            var machine = new MachineResource()
            {
                Name     = "Machine-CR-" + Guid.NewGuid().ToString().Substring(0, 8) + "-" + prefix.ToString("000"),
                Endpoint = new CloudRegionEndpointResource(),
            };

            // Spread across random environments that we've already created with SeaMonkey.
            var environments         = Repository.Environments.GetAll().Where(e => e.Name.Contains("Env-")).ToList();
            var numberOfEnvironments = environments.Count;
            var env1 = environments[Program.Rnd.Next(0, numberOfEnvironments)];
            var env2 = environments[Program.Rnd.Next(0, numberOfEnvironments)];
            var env3 = environments[Program.Rnd.Next(0, numberOfEnvironments)];
            var env4 = environments[Program.Rnd.Next(0, numberOfEnvironments)];
            var env5 = environments[Program.Rnd.Next(0, numberOfEnvironments)];

            machine.EnvironmentIds.Add(env1.Id);
            if (!machine.EnvironmentIds.Contains(env2.Id))
            {
                machine.EnvironmentIds.Add(env2.Id);
            }
            if (!machine.EnvironmentIds.Contains(env3.Id))
            {
                machine.EnvironmentIds.Add(env3.Id);
            }
            if (!machine.EnvironmentIds.Contains(env4.Id))
            {
                machine.EnvironmentIds.Add(env4.Id);
            }
            if (!machine.EnvironmentIds.Contains(env5.Id))
            {
                machine.EnvironmentIds.Add(env5.Id);
            }

            var rolesPerMachine = RolesPerMachine.Get();

            machine.Roles.Add("cloud-region"); // All machines get this role.
            for (int i = 0; i < rolesPerMachine; i++)
            {
                if (i < this.PossibleRoles.Length)
                {
                    machine.Roles.Add(this.PossibleRoles[i]);
                }
                else // Fallback in case PossibleRoles doesn't have enough values based on the LinearProbability (shouldn't happen if they are in sync).
                {
                    machine.Roles.Add(this.PossibleRoles[0]);
                }
            }

            return(machine);

            //return Repository.Machines.Create(machine);
        }
Example #8
0
        public void SyncGetTasksReturnsAllPages()
        {
            var machine = new MachineResource {
                Links = new LinkCollection {
                    { "TasksTemplate", $"{TestRootPath}api/machines/Machines-1/tasks{{?skip}}" }
                }
            };
            var repository = new Client.Repositories.MachineRepository(SyncClient);
            var tasks      = repository.GetTasks(machine);

            Assert.That(tasks.Count, Is.EqualTo(139));
        }
Example #9
0
        public string GetStatus(MachineResource machineResource)
        {
            if (IsHealthStatusPendingDeprication)
            {
                var status = machineResource.HealthStatus.ToString();
                if (machineResource.IsDisabled)
                {
                    status = status + " - Disabled";
                }
                return(status);
            }

            return(machineResource.Status.ToString());
        }
        public void WhenDeletingMachine_ThenDeleteTheMachineFromOctopusServer()
        {
            var thisMachine = new MachineResource();
            var machineRepo = _container.Resolve <IOctopusRepository>().Machines;

            machineRepo
            .FindByName(MachineName)
            .Returns(thisMachine);

            _sut.DeleteMachine();

            machineRepo
            .Received()
            .Delete(thisMachine);
        }
Example #11
0
        /// <summary>
        /// Creates a machine Resources.
        /// </summary>
        /// <param name="octRepository">The repository to call against.</param>
        /// <param name="name">Name of the new Machine.</param>
        /// <param name="roles">Roles to add to the Machine.</param>
        /// <param name="environmentIds">Environment Ids to add to the machine.</param>
        /// <param name="thumbprint">Thumbprint of the machine.</param>
        /// <param name="machineUri">Uri of the Machine.</param>
        /// <param name="machinePolicy">Policy of the Machine.</param>
        /// <returns>MachineResource</returns>
        public static MachineResource CreateMachineResource(OctopusRepository octRepository, string name, List <string> roles, List <string> environmentIds, string thumbprint, string machineUri, MachinePolicyResource machinePolicy)
        {
            var rolesReferenceCollection      = new ReferenceCollection(roles);
            var evironmentReferenceCollection = new ReferenceCollection(environmentIds);
            var machineToCreate = new MachineResource()
            {
                Name            = name,
                Roles           = rolesReferenceCollection,
                EnvironmentIds  = evironmentReferenceCollection,
                Thumbprint      = thumbprint,
                MachinePolicyId = machinePolicy.Id,
                Uri             = machineUri
            };

            return(octRepository.Machines.Create(machineToCreate));
        }
Example #12
0
        /// <summary>
        /// Creates a machine Resources with the default policy.
        /// </summary>
        /// <param name="octRepository">The repository to call against.</param>
        /// <param name="name">Name of the new Machine.</param>
        /// <param name="roles">Roles to add to the Machine.</param>
        /// <param name="environmentIds">Environment Ids to add to the machine.</param>
        /// <param name="thumbprint">Thumbprint of the machine.</param>
        /// <param name="machineUri">Uri of the Machine.</param>
        /// <returns>MachineResource</returns>
        public static MachineResource CreateMachineResource(OctopusRepository octRepository, string name, List <string> roles, List <string> environmentIds, string thumbprint, string machineUri)
        {
            var defaultMachinePolicy          = MachinePolicyHelper.GetMachinePolicyByName(octRepository, ResourceStrings.DefaultMachinePolicyName);
            var rolesReferenceCollection      = new ReferenceCollection(roles);
            var evironmentReferenceCollection = new ReferenceCollection(environmentIds);
            var machineToCreate = new MachineResource()
            {
                Name            = name,
                Roles           = rolesReferenceCollection,
                EnvironmentIds  = evironmentReferenceCollection,
                Thumbprint      = thumbprint,
                Uri             = machineUri,
                MachinePolicyId = defaultMachinePolicy.Id
            };

            return(octRepository.Machines.Create(machineToCreate));
        }
        public void SetUp()
        {
            _repository = new FakeOctopusRepository();
            _downloader = new Downloader(_repository);
            _uploader   = new Uploader(_repository);

            _model = new SystemModel(new[]
            {
                new Role("api", new List <string> {
                    "dev1", "dev2"
                }),
                new Role("csapi", new List <string> {
                    "dev1", "dev2"
                }),
                new Role("service", new List <string> {
                    "dev3"
                })
            }, new Tenant[]
            {
            }, new TenantTag[]
            {
            });

            foreach (var role in _model.Roles)
            {
                _repository.FakeMachineRoles.Add(role.Name);
            }

            foreach (var machineName in _model.Roles.SelectMany(x => x.Machines)
                     .Concat(_model.Tenants.SelectMany(x => x.Machines))
                     .Concat(_model.TenantTags.SelectMany(x => x.Machines)).Distinct())
            {
                var machine = new MachineResource {
                    Name = machineName
                };

                foreach (var machineRole in _model.Roles.Where(x => x.Machines.Contains(machineName)).Select(r => r.Name).ToList())
                {
                    machine.Roles.Add(machineRole);
                }
                _repository.Machines.Create(machine);
            }
        }
Example #14
0
        private void UploadTenantTagsMappingForMachine(MachineResource machineResource, IEnumerable <TenantTag> tenantTags, List <string> knownTags)
        {
            var unknownTags    = machineResource.TenantTags.Except(knownTags, _comparer).ToList();
            var tagsForMachine = tenantTags
                                 .Where(x => x.Machines.Contains(machineResource.Name, _comparer))
                                 .Select(x => x.Name)
                                 .Concat(unknownTags)
                                 .ToList();

            if (tagsForMachine.Count == 0)
            {
                return;
            }

            Logger.Info($"Updating {machineResource.Name} with TenantTags:");
            OutputMappingChanges(machineResource.TenantTags.ToList(), tagsForMachine, unknownTags);

            machineResource.TenantTags = new ReferenceCollection(tagsForMachine);
            _repository.Machines.Modify(machineResource);
        }
Example #15
0
        private void UploadRoleMappingForMachine(MachineResource machineResource, IEnumerable <Role> roles, IEnumerable <string> knownRoles)
        {
            var unknownRoles    = machineResource.Roles.Except(knownRoles, _comparer).ToList();
            var rolesForMachine = roles
                                  .Where(x => x.Machines.Contains(machineResource.Name, _comparer))
                                  .Select(x => x.Name)
                                  .Concat(unknownRoles)
                                  .ToList();

            if (rolesForMachine.Count == 0)
            {
                throw new InvalidOperationException($"Machine {machineResource.Name} has no roles");
            }

            Logger.Info($"Updating {machineResource.Name} with roles:");
            OutputMappingChanges(machineResource.Roles.ToList(), rolesForMachine, unknownRoles);

            machineResource.Roles = new ReferenceCollection(rolesForMachine);
            _repository.Machines.Modify(machineResource);
        }
        public void StepPackageEndpointInputs_IsSerializedAsObject()
        {
            var machine = new MachineResource
            {
                Id       = "test-target",
                Endpoint = new StepPackageEndpointResource
                {
                    Id     = "test-target",
                    Inputs = new { structureInput = "a", structuredInputB = new { accountId = "2" } }
                },
                Links = new LinkCollection {
                    { "Machines", $"{TestRootPath}api/machines" }
                }
            };
            var repository = new Client.Repositories.MachineRepository(SyncClient.Repository);
            var result     = repository.Create(machine);

            var stepPackageEndpoint = result.Endpoint as StepPackageEndpointResource;

            Assert.NotNull(stepPackageEndpoint);
            Assert.NotNull(stepPackageEndpoint.Inputs);
            Assert.IsNull(stepPackageEndpoint.Inputs as string);
        }
Example #17
0
 /// <summary>
 /// Adds a new Role to the machine.
 /// </summary>
 /// <param name="octRepository">The repository to call against.</param>
 /// <param name="machine">Machine to add the role to.</param>
 /// <param name="roleName">Role to add.</param>
 public static void AddRoleToMachine(OctopusRepository octRepository, MachineResource machine, string roleName)
 {
     machine.Roles.Add(roleName);
     octRepository.Machines.Modify(machine);
 }
        private async Task <bool> CanDeployToMachineCheckingRoles(IOctopusAsyncClient client, MachineResource machine, ReleaseResource release, string envId)
        {
            var deployTarget = await GetDeploymentTargetEnvironment(client, release, envId);

            var preview = await client.Repository.Releases.GetPreview(deployTarget);

            var stepsNeedRole = preview.StepsToExecute.Where(s => s.Roles.Any()).ToList();

            if (stepsNeedRole.Count < preview.StepsToExecute.Count)
            { // if any step doesn't require a role, then we can deploy the step to the machine.
                return(true);
            }

            return(stepsNeedRole.Any(step => step.Roles.Any(r => machine.Roles.Contains(r))));
        }
 private static OctopusMachineInfo Convert(MachineResource machine)
 {
     return(new OctopusMachineInfo(machine.Id, machine.Name, machine.IsDisabled));
 }