Esempio n. 1
0
        /// <summary>
        /// Creates a new instance of the <see cref="SummaryInfo"/> class copying values
        /// from the <see cref="Deployment.WindowsInstaller.SummaryInfo"/> object.
        /// </summary>
        /// <param name="info">The <see cref="Deployment.WindowsInstaller.SummaryInfo"/> from which to copy values.</param>
        /// <exception cref="ArgumentNullException">The parameter <paramref name="info"/> is null.</exception>
        internal SummaryInfo(Deployment.WindowsInstaller.SummaryInfo info)
        {
            if (null == info)
            {
                throw new ArgumentNullException("info");
            }

            this.Author = info.Author;
            this.CharacterCount = info.CharacterCount;
            this.CodePage = info.CodePage;
            this.Comments = info.Comments;
            this.CreateTime = info.CreateTime;
            this.CreatingApp = info.CreatingApp;
            this.Keywords = info.Keywords;
            this.LastPrintTime = info.LastPrintTime;
            this.LastSavedBy = info.LastSavedBy;
            this.LastSaveTime = info.LastSaveTime;
            this.PageCount = info.PageCount;
            this.RevisionNumber = info.RevisionNumber;
            this.Security = info.Security;
            this.Subject = info.Subject;
            this.Template = info.Template;
            this.Title = info.Title;
            this.WordCount = info.WordCount;
        }
    public DeploymentStatusClientTests()
    {
        var github = Helper.GetAuthenticatedClient();

        _deploymentsClient = github.Repository.Deployment;
        _context = github.CreateRepositoryContext("public-repo").Result;

        var blob = new NewBlob
        {
            Content = "Hello World!",
            Encoding = EncodingType.Utf8
        };

        var blobResult = github.Git.Blob.Create(_context.RepositoryOwner, _context.RepositoryName, blob).Result;

        var newTree = new NewTree();
        newTree.Tree.Add(new NewTreeItem
        {
            Type = TreeType.Blob,
            Mode = FileMode.File,
            Path = "README.md",
            Sha = blobResult.Sha
        });

        var treeResult = github.Git.Tree.Create(_context.RepositoryOwner, _context.RepositoryName, newTree).Result;
        var newCommit = new NewCommit("test-commit", treeResult.Sha);

        var commit = github.Git.Commit.Create(_context.RepositoryOwner, _context.RepositoryName, newCommit).Result;

        var newDeployment = new NewDeployment(commit.Sha) { AutoMerge = false };
        _deployment = _deploymentsClient.Create(_context.RepositoryOwner, _context.RepositoryName, newDeployment).Result;
    }
 public void NameSpecifiedAndRoleInstanceListDoesNotHaveMatchingRoleInstanceInDeployment()
 {
     var deployment = new Deployment
     {
         Url = AnyUrl(),
         RoleInstanceList = new RoleInstanceList
         {
             new RoleInstance()
         }
     };
     var winRmUri = new GetAzureWinRMUriStub(deployment)
     {
         Name = AnyString(),
         CommandRuntime = mockCommandRuntime
     };
     try
     {
         winRmUri.ExecuteCommandBody();
         Assert.Fail("Should never reach here.");
     }
     catch (ArgumentOutOfRangeException)
     {
     }
     Assert.AreEqual(0, mockCommandRuntime.OutputPipeline.Count, "Nothing should be written to output pipeline");
 }
 Deployment UpdateDeploymentSlofIfEmpty(Deployment deployment)
 {
     if (string.IsNullOrEmpty(deployment.DeploymentSlot))
     {
         deployment.DeploymentSlot = this.Slot;
     }
     return deployment;
 }
    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 static void KickItOutThereAlready(Deployment deployment, DeploymentArguments args)
        {
            _inspector = new DropkickDeploymentInspector(args.ServerMappings);

            if (args.Role != "ALL") _inspector.RolesToGet(args.Role.Split(','));

            var plan = _inspector.GetPlan(deployment);

            //HOW TO PLUG IN   args.Role
            //TODO: should be able to block here
            _actions[args.Command](plan);
        }
        public static DeploymentResult KickItOutThereAlready(Deployment deployment, DeploymentArguments args)
        {
            _inspector = new DropkickDeploymentInspector(args.ServerMappings);

            if (args.Role != "ALL") _inspector.RolesToGet(args.Role.Split(','));

            var plan = _inspector.GetPlan(deployment);
            plan.AbortOnError = args.AbortOnError;

            //HOW TO PLUG IN   args.Role
            //TODO: should be able to block here
            return plan.Run(args.Command);
        }
 //[TestMethod]
 public void NoUrlInDeployment()
 {
     var deployment = new Deployment();
     var winRmUri = new GetAzureWinRMUriStub(deployment)
     {
         CommandRuntime = mockCommandRuntime
     };
     try
     {
         winRmUri.ExecuteCommandBody();
         Assert.Fail("Should throw argument out of range exception");
     }
     catch (ArgumentOutOfRangeException)
     {
     }
 }
        public SelectTargetPortalDialog(Deployment deployment)
        {
            InitializeComponent();

            var targetPortals = deployment.Targets
                .SelectMany(target => target.Portals.Select(portal => new TargetPortalInfo(target, portal)))
                .ToList();

            cboTargetPortals.DataSource = targetPortals;

            //default to last deployed target portal
            if (_lastDeployedPortal != null)
            {
                var portalFromList = targetPortals.FirstOrDefault(portal => portal.TargetPortal == _lastDeployedPortal);
                if (portalFromList != null)
                    cboTargetPortals.SelectedItem = portalFromList;
            }
        }
    public DeploymentStatusClientTests()
    {
        _gitHubClient = new GitHubClient(new ProductHeaderValue("OctokitTests"))
        {
            Credentials = Helper.Credentials
        };

        _deploymentsClient = _gitHubClient.Repository.Deployment;

        var newRepository = new NewRepository
        {
            Name = Helper.MakeNameWithTimestamp("public-repo"),
            AutoInit = true
        };

        _repository = _gitHubClient.Repository.Create(newRepository).Result;
        _repositoryOwner = _repository.Owner.Login;

        var blob = new NewBlob
        {
            Content = "Hello World!",
            Encoding = EncodingType.Utf8
        };

        var blobResult = _gitHubClient.GitDatabase.Blob.Create(_repositoryOwner, _repository.Name, blob).Result;

        var newTree = new NewTree();
        newTree.Tree.Add(new NewTreeItem
        {
            Type = TreeType.Blob,
            Mode = FileMode.File,
            Path = "README.md",
            Sha = blobResult.Sha
        });

        var treeResult = _gitHubClient.GitDatabase.Tree.Create(_repositoryOwner, _repository.Name, newTree).Result;
        var newCommit = new NewCommit("test-commit", treeResult.Sha);
        _commit = _gitHubClient.GitDatabase.Commit.Create(_repositoryOwner, _repository.Name, newCommit).Result;

        var newDeployment = new NewDeployment { Ref = _commit.Sha };
        _deployment = _deploymentsClient.Create(_repositoryOwner, _repository.Name, newDeployment).Result;
    }
 public void NameSpecifiedAndNoRoleInstanceListInDeployment()
 {
     var deployment = new Deployment
     {
         Url = AnyUrl()
     };
     var winRmUri = new GetAzureWinRMUriStub(deployment)
     {
         CommandRuntime = mockCommandRuntime,
         Name = AnyString()
     };
     try
     {
         winRmUri.ExecuteCommandBody();
         Assert.Fail("Should throw argument out of range exception");
     }
     catch (ArgumentOutOfRangeException)
     {
     }
 }
        public DeploymentInfoContext(Deployment innerDeployment)
        {
            this.innerDeployment = innerDeployment;

            if (this.innerDeployment.RoleInstanceList != null)
            {
                this.RoleInstanceList = new List<AzureDeploymentCmdlets.Concrete.RoleInstance>();
                foreach (var roleInstance in this.innerDeployment.RoleInstanceList)
                {
                    this.RoleInstanceList.Add(new AzureDeploymentCmdlets.Concrete.RoleInstance(roleInstance));
                }
            }

            if (!string.IsNullOrEmpty(this.innerDeployment.Configuration))
            {
                string xmlString = ServiceManagementHelper.DecodeFromBase64String(this.innerDeployment.Configuration);

                XDocument doc = null;
                using (var stringReader = new StringReader(xmlString))
                {
                    XmlReader reader = XmlReader.Create(stringReader);
                    doc = XDocument.Load(reader);
                }

                this.OSVersion = doc.Root.Attribute("osVersion") != null ?
                                 doc.Root.Attribute("osVersion").Value :
                                 string.Empty;

                this.RolesConfiguration = new Dictionary<string, RoleConfiguration>();

                var roles = doc.Root.Descendants(this.ns + "Role");

                foreach (var role in roles)
                {
                    this.RolesConfiguration.Add(role.Attribute("name").Value, new RoleConfiguration(role));
                }
            }
        }
    public DeploymentStatusClientTests()
    {
        var gitHubClient = Helper.GetAuthenticatedClient();
        _deploymentsClient = gitHubClient.Repository.Deployment;

        var newRepository = new NewRepository(Helper.MakeNameWithTimestamp("public-repo"))
        {
            AutoInit = true
        };

        _repository = gitHubClient.Repository.Create(newRepository).Result;
        _repositoryOwner = _repository.Owner.Login;

        var blob = new NewBlob
        {
            Content = "Hello World!",
            Encoding = EncodingType.Utf8
        };

        var blobResult = gitHubClient.GitDatabase.Blob.Create(_repositoryOwner, _repository.Name, blob).Result;

        var newTree = new NewTree();
        newTree.Tree.Add(new NewTreeItem
        {
            Type = TreeType.Blob,
            Mode = FileMode.File,
            Path = "README.md",
            Sha = blobResult.Sha
        });

        var treeResult = gitHubClient.GitDatabase.Tree.Create(_repositoryOwner, _repository.Name, newTree).Result;
        var newCommit = new NewCommit("test-commit", treeResult.Sha);
        var commit = gitHubClient.GitDatabase.Commit.Create(_repositoryOwner, _repository.Name, newCommit).Result;

        var newDeployment = new NewDeployment(commit.Sha) { AutoMerge = false };
        _deployment = _deploymentsClient.Create(_repositoryOwner, _repository.Name, newDeployment).Result;
    }
Esempio n. 14
0
 public static DeploymentAction NewUpdateAction(Deployment deployment)
 {
     return(new DeploymentAction(ActionType.Update, deployment));
 }
 public void NoNameSpecifiedAndRoleInstanceListWithSingleRoleInstanceWithSingleNonWinRMInputEndpointInDeployment()
 {
     var deployment = new Deployment
     {
         Url = AnyUrl(),
         RoleInstanceList = new RoleInstanceList
         {
             new RoleInstance
             {
                 InstanceEndpoints = new InstanceEndpointList
                 {
                     new InstanceEndpoint()
                 }
             }
         }
     };
     var winRmUri = new GetAzureWinRMUriStub(deployment)
     {
         CommandRuntime = mockCommandRuntime
     };
     winRmUri.ExecuteCommandBody();
     Assert.AreEqual(0, mockCommandRuntime.OutputPipeline.Count, "Nothing should be written to output pipeline");
 }
Esempio n. 16
0
 private void BeginDeployment(string resourceGroupName, string deploymentName, Deployment deployment)
 {
     if (resourceGroupName == null)
     {
         this.ResourceManagementClient.Deployments.BeginCreateOrUpdateAtSubscriptionScope(deploymentName, deployment);
     }
     else
     {
         this.ResourceManagementClient.Deployments.BeginCreateOrUpdate(resourceGroupName, deploymentName, deployment);
     }
 }
Esempio n. 17
0
        private void WriteDeploymentProgress(string resourceGroup, string deploymentName, Deployment deployment)
        {
            const string normalStatusFormat  = "Resource {0} '{1}' provisioning status is {2}";
            const string failureStatusFormat = "Resource {0} '{1}' failed with message '{2}'";
            List <DeploymentOperation> newOperations;

            var result = this.ListDeploymentOperations(resourceGroup, deploymentName);

            newOperations = GetNewOperations(operations, result);
            operations.AddRange(newOperations);

            while (!string.IsNullOrEmpty(result.NextPageLink))
            {
                result        = this.ListNextDeploymentOperations(resourceGroup, result.NextPageLink);
                newOperations = GetNewOperations(operations, result);
                operations.AddRange(newOperations);
            }

            foreach (DeploymentOperation operation in newOperations)
            {
                string statusMessage;

                if (operation.Properties.ProvisioningState != ProvisioningState.Failed.ToString())
                {
                    if (operation.Properties.TargetResource != null)
                    {
                        statusMessage = string.Format(normalStatusFormat,
                                                      operation.Properties.TargetResource.ResourceType,
                                                      operation.Properties.TargetResource.ResourceName,
                                                      operation.Properties.ProvisioningState.ToLower());

                        WriteVerbose(statusMessage);
                    }
                }
                else
                {
                    string errorMessage = operation.Properties.StatusMessage.ToString();

                    if (operation.Properties.TargetResource != null)
                    {
                        statusMessage = string.Format(failureStatusFormat,
                                                      operation.Properties.TargetResource.ResourceType,
                                                      operation.Properties.TargetResource.ResourceName,
                                                      errorMessage);

                        WriteError(statusMessage);
                    }
                    else
                    {
                        WriteError(errorMessage);
                    }

                    List <string> detailedMessage = ParseDetailErrorMessage(operation.Properties.StatusMessage.ToString());

                    if (detailedMessage != null && detailedMessage.Count > 0)
                    {
                        detailedMessage.ForEach(s => WriteError(s));
                    }
                }
            }
        }
Esempio n. 18
0
        private TemplateValidationInfo CheckBasicDeploymentErrors(string resourceGroup, string deploymentName, Deployment deployment)
        {
            DeploymentValidateResponse validationResult = ResourceManagementClient.Deployments.Validate(
                resourceGroup,
                deploymentName,
                deployment);

            return(new TemplateValidationInfo(validationResult));
        }
Esempio n. 19
0
        private static IEnumerator ConnectToLocatorAsync(WorkerConnectionParameters parameters, Deployment deployment, Action <Connection> onConnection)
        {
            var locator          = CreateLocator(parameters);
            var connectionFuture = locator.ConnectAsync(deployment.DeploymentName, parameters.ConnectionParameters, OnQueueStatusThunk);

            // ReSharper disable once AccessToDisposedClosure
            var wait = new WaitUntil(() => connectionFuture.Get(ReturnImmediatelyMillis).HasValue);

            yield return(wait);

            onConnection(connectionFuture.Get());

            connectionFuture.Dispose();
            locator.Dispose();
        }
        public void NoNameSpecifiedAndRoleInstanceListWithSingleRoleInstanceWithSingleWinRMInputEndpointInDeployment()
        {
            var deployment = new Deployment
            {
                Url = deploymentUrl,
                RoleInstanceList = new RoleInstanceList
                {
                    new RoleInstance
                    {
                        InstanceEndpoints = new InstanceEndpointList
                        {
                            new InstanceEndpoint
                            {
                                LocalPort = WinRMConstants.HttpsListenerPort,
                                Name = WinRMConstants.EndpointName,
                                PublicPort = publicPort
                            }
                        }
                    }
                }
            };
            var winRmUri = new GetAzureWinRMUriStub(deployment)
            {
                CommandRuntime = mockCommandRuntime
            };
            winRmUri.ExecuteCommandBody();
            Assert.AreEqual(1, mockCommandRuntime.OutputPipeline.Count, "One item should be in the output pipeline");

            var uris = mockCommandRuntime.OutputPipeline[0] as List<Uri>;
            Assert.IsNotNull(uris, "List<Uri> is expected");

            Uri uri = uris[0];
            var builder = new UriBuilder("https", deploymentUrl.Host, publicPort);
            Assert.AreEqual(builder.Uri, uri);
        }
Esempio n. 21
0
 public static Deployment CreateDeployment(int instanceId, string computerName, int lowKey, int highKey, global::System.DateTime creationTime, global::System.DateTime lastModifiedTime)
 {
     Deployment deployment = new Deployment();
     deployment.InstanceId = instanceId;
     deployment.ComputerName = computerName;
     deployment.LowKey = lowKey;
     deployment.HighKey = highKey;
     deployment.CreationTime = creationTime;
     deployment.LastModifiedTime = lastModifiedTime;
     return deployment;
 }
        private string GetDeploymentId(PublishContext context)
        {
            Deployment deployment = new Deployment();

            do
            {
                // If a deployment has many roles to initialize, this
                // thread must throttle requests so the Azure portal
                // doesn't reply with a "too many requests" error
                Thread.Sleep(SleepDuration);

                try
                {
                    deployment = new Deployment(
                        ComputeClient.Deployments.GetBySlot(context.ServiceName,
                        GetSlot(context.ServiceSettings.Slot)));
                }
                catch (CloudException ex)
                {
                    if (ex.Response.StatusCode != HttpStatusCode.InternalServerError)
                    {
                        throw;
                    }
                }
            }
            while (deployment.Status != DeploymentStatus.Starting && deployment.Status != DeploymentStatus.Running);

            return deployment.PrivateID;
        }
        /// <summary>
        /// Verify a deployment exists
        /// </summary>
        /// <param name="serviceName"></param>
        /// <param name="slot"></param>
        private void VerifyDeployment()
        {
            try
            {
                SafeWriteObjectWithTimestamp(Resources.PublishStartingMessage);
                SafeWriteObjectWithTimestamp(Resources.PublishInitializingMessage);

                Dictionary<string, RoleInstance> roleInstanceSnapshot = new Dictionary<string, RoleInstance>();

                // Continue polling for deployment until all of the roles
                // indicate they're ready
                Deployment deployment = new Deployment();
                do
                {
                    deployment = RetryCall(subscription =>
                        Channel.GetDeploymentBySlot(
                            subscription,
                            _hostedServiceName,
                            _deploymentSettings.ServiceSettings.Slot));

                    // The goal of this loop is to output a message whenever the status of a role
                    // instance CHANGES. To do that, we have to remember the last status of all role instances
                    // and that's what the roleInstanceSnapshot array is for
                    foreach (RoleInstance currentInstance in deployment.RoleInstanceList)
                    {
                        // We only care about these three statuses, ignore other intermediate statuses
                        if (String.Equals(currentInstance.InstanceStatus, RoleInstanceStatus.Busy) ||
                            String.Equals(currentInstance.InstanceStatus, RoleInstanceStatus.Ready) ||
                            String.Equals(currentInstance.InstanceStatus, RoleInstanceStatus.Initializing))
                        {
                            bool createdOrChanged = false;

                            // InstanceName is unique and concatenates the role name and instance name
                            if (roleInstanceSnapshot.ContainsKey(currentInstance.InstanceName))
                            {
                                // If we already have a snapshot of that role instance, update it
                                RoleInstance previousInstance = roleInstanceSnapshot[currentInstance.InstanceName];
                                if (!String.Equals(previousInstance.InstanceStatus, currentInstance.InstanceStatus))
                                {
                                    // If the instance status changed, we need to output a message
                                    previousInstance.InstanceStatus = currentInstance.InstanceStatus;
                                    createdOrChanged = true;
                                }
                            }
                            else
                            {
                                // If this is the first time we run through, we also need to output a message
                                roleInstanceSnapshot[currentInstance.InstanceName] = currentInstance;
                                createdOrChanged = true;
                            }

                            if (createdOrChanged)
                            {
                                string statusResource;
                                switch (currentInstance.InstanceStatus)
                                {
                                    case RoleInstanceStatus.Busy:
                                        statusResource = Resources.PublishInstanceStatusBusy;
                                        break;

                                    case RoleInstanceStatus.Ready:
                                        statusResource = Resources.PublishInstanceStatusReady;
                                        break;

                                    default:
                                        statusResource = Resources.PublishInstanceStatusCreating;
                                        break;
                                }

                                SafeWriteObjectWithTimestamp(String.Format(Resources.PublishInstanceStatusMessage,
                                    currentInstance.InstanceName, currentInstance.RoleName, statusResource));

                            }
                        }
                    }

                    // If a deployment has many roles to initialize, this
                    // thread must throttle requests so the Azure portal
                    // doesn't reply with a "too many requests" error
                    Thread.Sleep(int.Parse(Resources.StandardRetryDelayInMs));
                }
                while (deployment.RoleInstanceList.Any(
                    r => r.InstanceStatus != RoleInstanceStatus.Ready));

                if (CanGenerateUrlForDeploymentSlot())
                {
                    SafeWriteObjectWithTimestamp(
                        Resources.PublishCreatedWebsiteMessage,
                        string.Format(Resources.ServiceUrl, _hostedServiceName));
                }
                else
                {
                    SafeWriteObjectWithTimestamp(
                        Resources.PublishCreatedWebsiteLaunchNotSupportedMessage);
                }

            }
            catch (EndpointNotFoundException)
            {
                throw new InvalidOperationException(
                    string.Format(
                        Resources.CannotFindDeployment,
                        _hostedServiceName,
                        _deploymentSettings.ServiceSettings.Slot));
            }
        }
        public DeploymentInfoContext(Deployment deployment)
        {
            this.Slot = deployment.DeploymentSlot;
            this.Name = deployment.Name;
            this.DeploymentName = deployment.Name;
            this.Url = deployment.Url;
            this.Status = deployment.Status;
            this.DeploymentId = deployment.PrivateID;
            this.VNetName = deployment.VirtualNetworkName;
            this.SdkVersion = deployment.SdkVersion;
            this.DnsSettings = deployment.Dns;

            if (deployment.RollbackAllowed.HasValue)
            {
                this.RollbackAllowed = deployment.RollbackAllowed;
            }

            if (deployment.UpgradeStatus != null)
            {
                this.CurrentUpgradeDomain = deployment.UpgradeStatus.CurrentUpgradeDomain;
                this.CurrentUpgradeDomainState = deployment.UpgradeStatus.CurrentUpgradeDomainState;
                this.UpgradeType = deployment.UpgradeStatus.UpgradeType;
            }

            this.Configuration = string.IsNullOrEmpty(deployment.Configuration)
                                     ? string.Empty
                                     : ServiceManagementHelper.DecodeFromBase64String(deployment.Configuration);

            this.Label = string.IsNullOrEmpty(deployment.Label)
                             ? string.Empty
                             : ServiceManagementHelper.DecodeFromBase64String(deployment.Label);

            if (deployment.RoleInstanceList != null)
            {
                this.RoleInstanceList = new List<RoleInstance>();
                foreach (var roleInstance in deployment.RoleInstanceList)
                {
                    this.RoleInstanceList.Add(roleInstance);
                }
            }

            if (!string.IsNullOrEmpty(deployment.Configuration))
            {
                string xmlString = this.Configuration;

                XDocument doc;
                using (var stringReader = new StringReader(xmlString))
                {
                    XmlReader reader = XmlReader.Create(stringReader);
                    doc = XDocument.Load(reader);
                }

                this.OSVersion = doc.Root.Attribute("osVersion") != null ?
                                 doc.Root.Attribute("osVersion").Value :
                                 string.Empty;

                this.RolesConfiguration = new Dictionary<string, RoleConfiguration>();

                var roles = doc.Root.Descendants(this.ns + "Role");

                foreach (var role in roles)
                {
                    this.RolesConfiguration.Add(role.Attribute("name").Value, new RoleConfiguration(role));
                }
            }
        }
 public void NameSpecifiedAndRoleInstanceListWithSingleRoleInstanceWithoutEndpointInDeployment()
 {
     var deployment = new Deployment
     {
         Url = deploymentUrl,
         RoleInstanceList = new RoleInstanceList
         {
             new RoleInstance
             {
                 RoleName = roleName,
             }
         }
     };
     var winRmUri = new GetAzureWinRMUriStub(deployment)
     {
         Name = roleName,
         CommandRuntime = mockCommandRuntime
     };
     try
     {
         winRmUri.ExecuteCommandBody();
     }
     catch (ArgumentOutOfRangeException)
     {
     }
     Assert.AreEqual(0, mockCommandRuntime.OutputPipeline.Count, "There should be no item in the output pipeline");
 }
        protected void ValidateDeployment()
        {
            Slot = string.IsNullOrEmpty(Slot) ? DeploymentSlotType.Production : Slot;

            Deployment = Channel.GetDeploymentBySlot(CurrentSubscription.SubscriptionId, ServiceName, Slot);
            if (Deployment == null)
            {
                throw new Exception(string.Format(Resources.ServiceExtensionCannotFindDeployment, ServiceName, Slot));
            }

            if (Deployment.ExtensionConfiguration == null)
            {
                Deployment.ExtensionConfiguration = new ExtensionConfiguration
                {
                    AllRoles = new AllRoles(),
                    NamedRoles = new NamedRoles()
                };
            }
        }
Esempio n. 27
0
        public void NewAzureVMProcess()
        {
            SubscriptionData currentSubscription = this.GetCurrentSubscription();

            CloudStorageAccount currentStorage = null;
            try
            {
                currentStorage = CloudStorageAccountFactory.GetCurrentCloudStorageAccount(Channel, currentSubscription);
            }
            catch (ServiceManagementClientException) // couldn't access
            {
                throw new ArgumentException("CurrentStorageAccount is not accessible. Ensure the current storage account is accessible and in the same location or affinity group as your cloud service.");
            }
            if (currentStorage == null) // not set
            {
                throw new ArgumentException("CurrentStorageAccount is not set. Use Set-AzureSubscription subname -CurrentStorageAccount storage account to set it.");
            }

            Operation lastOperation = null;

            using (new OperationContextScope(Channel.ToContextChannel()))
            {
                try
                {
                    if (this.ParameterSetName.Equals("CreateService", StringComparison.OrdinalIgnoreCase) == true)
                    {
                        var chsi = new CreateHostedServiceInput
                        {
                            AffinityGroup = this.AffinityGroup,
                            Location = this.Location,
                            ServiceName = this.ServiceName,
                            Description = this.ServiceDescription ??
                                            String.Format("Implicitly created hosted service{0}",DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd HH:mm")),
                            Label = this.ServiceLabel ?? this.ServiceName
                        };

                        ExecuteClientAction(chsi, CommandRuntime + " - Create Cloud Service", s => this.Channel.CreateHostedService(s, chsi));
                    }
                }
                catch (ServiceManagementClientException ex)
                {
                    this.WriteErrorDetails(ex);
                    return;
                }
            }

            if (lastOperation != null && string.Compare(lastOperation.Status, OperationState.Failed, StringComparison.OrdinalIgnoreCase) == 0)
            {
                return;
            }

            foreach (var vm in VMs)
            {
                var configuration = vm.ConfigurationSets.OfType<WindowsProvisioningConfigurationSet>().FirstOrDefault();
                if (configuration != null)
                {
                    if (vm.WinRMCertificate != null)
                    {
                        if(!CertUtils.HasExportablePrivateKey(vm.WinRMCertificate))
                        {
                            throw new ArgumentException("WinRMCertificate needs to have an exportable private key.");
                        }
                        var operationDescription = string.Format("{0} - Uploading WinRMCertificate: {1}", CommandRuntime, vm.WinRMCertificate.Thumbprint);
                        var certificateFile = CertUtils.Create(vm.WinRMCertificate);
                        ExecuteClientActionInOCS(null, operationDescription, s => this.Channel.AddCertificates(s, this.ServiceName, certificateFile));
                    }
                    var certificateFilesWithThumbprint = from c in vm.X509Certificates
                                                         select new
                                                                {
                                                                    c.Thumbprint,
                                                                    CertificateFile = CertUtils.Create(c, vm.NoExportPrivateKey)
                                                                };
                    foreach (var current in certificateFilesWithThumbprint.ToList())
                    {
                        var operationDescription = string.Format("{0} - Uploading Certificate: {1}", CommandRuntime, current.Thumbprint);
                        ExecuteClientActionInOCS(null, operationDescription, s => this.Channel.AddCertificates(s, this.ServiceName, current.CertificateFile));
                    }
                }
            }

            var persistentVMs = this.VMs.Select(vm => CreatePersistenVMRole(vm, currentStorage)).ToList();

            // If the current deployment doesn't exist set it create it
            if (CurrentDeployment == null)
            {
                using (new OperationContextScope(Channel.ToContextChannel()))
                {
                    try
                    {
                        var deployment = new Deployment
                        {
                            DeploymentSlot = "Production",
                            Name = this.DeploymentName ?? this.ServiceName,
                            Label = this.DeploymentLabel ?? this.ServiceName,
                            RoleList = new RoleList(new List<Role> { persistentVMs[0] }),
                            VirtualNetworkName = this.VNetName
                        };

                        if (this.DnsSettings != null)
                        {
                            deployment.Dns = new DnsSettings {DnsServers = new DnsServerList()};
                            foreach (var dns in this.DnsSettings)
                            {
                                deployment.Dns.DnsServers.Add(dns);
                            }
                        }

                        var operationDescription = string.Format("{0} - Create Deployment with VM {1}", CommandRuntime, persistentVMs[0].RoleName);
                        ExecuteClientAction(deployment, operationDescription, s => this.Channel.CreateDeployment(s, this.ServiceName, deployment));

                        if(this.WaitForBoot.IsPresent)
                        {
                            WaitForRoleToBoot(persistentVMs[0].RoleName);
                        }
                    }
                    catch (ServiceManagementClientException ex)
                    {
                        if (ex.HttpStatus == HttpStatusCode.NotFound)
                        {
                            throw new Exception("Cloud Service does not exist. Specify -Location or -AffinityGroup to create one.");
                        }
                        else
                        {
                            this.WriteErrorDetails(ex);
                        }
                        return;
                    }

                    this.createdDeployment = true;
                }
            }
            else
            {
                if (this.VNetName != null || this.DnsSettings != null || !string.IsNullOrEmpty(this.DeploymentLabel) || !string.IsNullOrEmpty(this.DeploymentName))
                {
                    WriteWarning("VNetName, DnsSettings, DeploymentLabel or DeploymentName Name can only be specified on new deployments.");
                }
            }

            if (this.createdDeployment == false && CurrentDeployment != null)
            {
                this.DeploymentName = CurrentDeployment.Name;
            }

            int startingVM = (this.createdDeployment == true) ? 1 : 0;

            for (int i = startingVM; i < persistentVMs.Count; i++)
            {
                var operationDescription = string.Format("{0} - Create VM {1}", CommandRuntime, persistentVMs[i].RoleName);
                ExecuteClientActionInOCS(persistentVMs[i],operationDescription, s => this.Channel.AddRole(s, this.ServiceName, this.DeploymentName ?? this.ServiceName, persistentVMs[i]));
            }

            if(this.WaitForBoot.IsPresent)
            {
                for (int i = startingVM; i < persistentVMs.Count; i++)
                {
                    WaitForRoleToBoot(persistentVMs[i].RoleName);
                }
            }
        }
Esempio n. 28
0
        public static ConnectionInfo ToConnectionInfo(Func <string, IUserSecretsManager> userSecretsManagerFactory, Deployment options)
        {
            ValidateAuth(options.AuthType, options.Auth);

            switch (options.AuthType)
            {
            case AuthType.Classic:
                return(FromClassicAuth(options.Auth, options.Settings.Host));

            case AuthType.PrivateKeyFile:
                return(FromPrivateKeyFile(options));

            case AuthType.UserSecrets:
                return(FromUserSecrets(userSecretsManagerFactory, options));
            }

            throw new ArgumentOutOfRangeException($"Authorization for authorization type '{options.AuthType}' cannot be parsed. It should be a string in the form of {Sample(options.AuthType)}");
        }
Esempio n. 29
0
        private void VerifyDeployment(PublishContext context)
        {
            try
            {
                WriteVerboseWithTimestamp(Resources.PublishInitializingMessage);

                Dictionary<string, RoleInstance> roleInstanceSnapshot = new Dictionary<string, RoleInstance>();

                // Continue polling for deployment until all of the roles
                // indicate they're ready
                Deployment deployment = new Deployment();
                do
                {
                    deployment = ServiceManagementChannel.GetDeploymentBySlot(
                        subscriptionId,
                        context.ServiceName,
                        context.ServiceSettings.Slot);

                    // The goal of this loop is to output a message whenever the status of a role
                    // instance CHANGES. To do that, we have to remember the last status of all role instances
                    // and that's what the roleInstanceSnapshot array is for
                    foreach (RoleInstance currentInstance in deployment.RoleInstanceList)
                    {
                        // We only care about these three statuses, ignore other intermediate statuses
                        if (string.Equals(currentInstance.InstanceStatus, RoleInstanceStatus.BusyRole) ||
                            string.Equals(currentInstance.InstanceStatus, RoleInstanceStatus.ReadyRole) ||
                            string.Equals(currentInstance.InstanceStatus, RoleInstanceStatus.CreatingRole))
                        {
                            bool createdOrChanged = false;

                            // InstanceName is unique and concatenates the role name and instance name
                            if (roleInstanceSnapshot.ContainsKey(currentInstance.InstanceName))
                            {
                                // If we already have a snapshot of that role instance, update it
                                RoleInstance previousInstance = roleInstanceSnapshot[currentInstance.InstanceName];
                                if (!string.Equals(previousInstance.InstanceStatus, currentInstance.InstanceStatus))
                                {
                                    // If the instance status changed, we need to output a message
                                    previousInstance.InstanceStatus = currentInstance.InstanceStatus;
                                    createdOrChanged = true;
                                }
                            }
                            else
                            {
                                // If this is the first time we run through, we also need to output a message
                                roleInstanceSnapshot[currentInstance.InstanceName] = currentInstance;
                                createdOrChanged = true;
                            }

                            if (createdOrChanged)
                            {
                                string statusResource;
                                switch (currentInstance.InstanceStatus)
                                {
                                    case RoleInstanceStatus.BusyRole:
                                        statusResource = Resources.PublishInstanceStatusBusy;
                                        break;

                                    case RoleInstanceStatus.ReadyRole:
                                        statusResource = Resources.PublishInstanceStatusReady;
                                        break;

                                    default:
                                        statusResource = Resources.PublishInstanceStatusCreating;
                                        break;
                                }

                                WriteVerboseWithTimestamp(
                                    Resources.PublishInstanceStatusMessage,
                                    currentInstance.InstanceName,
                                    currentInstance.RoleName,
                                    statusResource);
                            }
                        }
                    }

                    // If a deployment has many roles to initialize, this
                    // thread must throttle requests so the Azure portal
                    // doesn't reply with a "too many requests" error
                    Thread.Sleep(SleepDuration);
                }
                while (deployment.RoleInstanceList.Any(r => r.InstanceStatus != RoleInstanceStatus.ReadyRole));

                WriteVerboseWithTimestamp(Resources.PublishCreatedWebsiteMessage, deployment.Url);

            }
            catch (ServiceManagementClientException)
            {
                throw new InvalidOperationException(
                    string.Format(Resources.CannotFindDeployment, context.ServiceName, context.ServiceSettings.Slot));
            }
        }
 public GetAzureWinRMUriStub(Deployment currentDeployment)
 {
     this.CurrentDeployment = currentDeployment;
 }
Esempio n. 31
0
 public void AddToDeployment(Deployment deployment)
 {
     base.AddObject("Deployment", deployment);
 }
Esempio n. 32
0
        public void NewAzureVMProcess()
        {
            SubscriptionData currentSubscription = this.GetCurrentSubscription();
            CloudStorageAccount currentStorage = null;
            try
            {
                currentStorage = currentSubscription.GetCurrentStorageAccount(Channel);
            }
            catch (EndpointNotFoundException) // couldn't access
            {
                throw new ArgumentException("CurrentStorageAccount is not accessible. Ensure the current storage account is accessible and in the same location or affinity group as your cloud service.");
            }
            if (currentStorage == null) // not set
            {
                throw new ArgumentException("CurrentStorageAccount is not set. Use Set-AzureSubscription subname -CurrentStorageAccount storageaccount to set it.");
            }

            var vm = new PersistentVMRole
            {
                AvailabilitySetName = AvailabilitySetName,
                ConfigurationSets = new Collection<ConfigurationSet>(),
                DataVirtualHardDisks = new Collection<DataVirtualHardDisk>(),
                RoleName = String.IsNullOrEmpty(Name) ? ServiceName : Name, // default like the portal
                RoleSize = String.IsNullOrEmpty(InstanceSize) ? null : InstanceSize,
                RoleType = "PersistentVMRole",
                Label = ServiceManagementHelper.EncodeToBase64String(ServiceName)
            };

            vm.OSVirtualHardDisk = new OSVirtualHardDisk()
            {
                DiskName = null,
                SourceImageName = ImageName,
                MediaLink = string.IsNullOrEmpty(MediaLocation) ? null : new Uri(MediaLocation),
                HostCaching = HostCaching
            };

            if (vm.OSVirtualHardDisk.MediaLink == null && String.IsNullOrEmpty(vm.OSVirtualHardDisk.DiskName))
            {
                DateTime dtCreated = DateTime.Now;
                string vhdname = String.Format("{0}-{1}-{2}-{3}-{4}-{5}.vhd", this.ServiceName, vm.RoleName, dtCreated.Year, dtCreated.Month, dtCreated.Day, dtCreated.Millisecond);
                string blobEndpoint = currentStorage.BlobEndpoint.AbsoluteUri;
                if (blobEndpoint.EndsWith("/") == false)
                    blobEndpoint += "/";
                vm.OSVirtualHardDisk.MediaLink = new Uri(blobEndpoint + "vhds/" + vhdname);
            }

            NetworkConfigurationSet netConfig = new NetworkConfigurationSet();
            netConfig.InputEndpoints = new Collection<InputEndpoint>();
            if (SubnetNames != null)
            {
                netConfig.SubnetNames = new SubnetNamesCollection();
                foreach (string subnet in SubnetNames)
                {
                    netConfig.SubnetNames.Add(subnet);
                }
            }

            if (ParameterSetName.Equals("Windows", StringComparison.OrdinalIgnoreCase))
            {
                WindowsProvisioningConfigurationSet windowsConfig = new WindowsProvisioningConfigurationSet
                {
                    AdminPassword = Password,
                    ComputerName = string.IsNullOrEmpty(Name) ? ServiceName : Name,
                    EnableAutomaticUpdates = true,
                    ResetPasswordOnFirstLogon = false,
                    StoredCertificateSettings = Certificates
                };

                InputEndpoint rdpEndpoint = new InputEndpoint { LocalPort = 3389, Protocol = "tcp", Name = "RemoteDesktop" };

                netConfig.InputEndpoints.Add(rdpEndpoint);
                vm.ConfigurationSets.Add(windowsConfig);
                vm.ConfigurationSets.Add(netConfig);
            }
            else
            {
                LinuxProvisioningConfigurationSet linuxConfig = new LinuxProvisioningConfigurationSet();
                linuxConfig.HostName = string.IsNullOrEmpty(this.Name) ? this.ServiceName : this.Name;
                linuxConfig.UserName = this.LinuxUser;
                linuxConfig.UserPassword = this.Password;
                linuxConfig.DisableSshPasswordAuthentication = false;

                if (this.SSHKeyPairs != null && this.SSHKeyPairs.Count > 0 || this.SSHPublicKeys != null && this.SSHPublicKeys.Count > 0)
                {
                    linuxConfig.SSH = new LinuxProvisioningConfigurationSet.SSHSettings();
                    linuxConfig.SSH.PublicKeys = this.SSHPublicKeys;
                    linuxConfig.SSH.KeyPairs = this.SSHKeyPairs;
                }

                InputEndpoint rdpEndpoint = new InputEndpoint();
                rdpEndpoint.LocalPort = 22;
                rdpEndpoint.Protocol = "tcp";
                rdpEndpoint.Name = "SSH";
                netConfig.InputEndpoints.Add(rdpEndpoint);
                vm.ConfigurationSets.Add(linuxConfig);
                vm.ConfigurationSets.Add(netConfig);
            }

            string CreateCloudServiceOperationID = String.Empty;
            string CreateDeploymentOperationID = String.Empty;
            List<String> CreateVMOperationIDs = new List<String>();
            Operation lastOperation = null;

            bool ServiceExists = DoesCloudServiceExist(this.ServiceName);

            if (string.IsNullOrEmpty(this.Location) == false || string.IsNullOrEmpty(AffinityGroup) == false || (!String.IsNullOrEmpty(VNetName) && ServiceExists == false))
            {
                using (new OperationContextScope((IContextChannel)Channel))
                {
                    try
                    {
                        //Implicitly created hosted service2012-05-07 23:12

                        // Create the Cloud Service when
                        // Location or Affinity Group is Specified
                        // or VNET is specified and the service doesn't exist
                        var chsi = new CreateHostedServiceInput
                        {
                            AffinityGroup = this.AffinityGroup,
                            Location = this.Location,
                            ServiceName = this.ServiceName,
                            Description = String.Format("Implicitly created hosted service{0}", DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd HH:mm")),
                            Label = ServiceManagementHelper.EncodeToBase64String(this.ServiceName)
                        };

                        ExecuteClientAction(chsi, CommandRuntime + " - Create Cloud Service", s => this.Channel.CreateHostedService(s, chsi), WaitForOperation);
                    }

                    catch (CommunicationException ex)
                    {
                        this.WriteErrorDetails(ex);
                        return;
                    }
                }
            }
            if (lastOperation != null && string.Compare(lastOperation.Status, OperationState.Failed, StringComparison.OrdinalIgnoreCase) == 0)
                return;

            // If the current deployment doesn't exist set it create it
            if (CurrentDeployment == null)
            {
                using (new OperationContextScope((IContextChannel)Channel))
                {
                    try
                    {
                        var deployment = new Deployment
                        {
                            DeploymentSlot = "Production",
                            Name = this.ServiceName,
                            Label = this.ServiceName,
                            RoleList = new RoleList(new List<Role> { vm }),
                            VirtualNetworkName = this.VNetName

                        };

                        if (this.DnsSettings != null)
                        {
                            deployment.Dns = new DnsSettings();
                            deployment.Dns.DnsServers = new DnsServerList();
                            foreach (DnsServer dns in this.DnsSettings)
                                deployment.Dns.DnsServers.Add(dns);
                        }

                        ExecuteClientAction(deployment, CommandRuntime + " - Create Deployment with VM " + vm.RoleName, s => this.Channel.CreateDeployment(s, this.ServiceName, deployment), WaitForOperation);
                    }

                    catch (CommunicationException ex)
                    {
                        if (ex is EndpointNotFoundException)
                        {
                            throw new Exception("Cloud Service does not exist. Specify -Location or -Affinity group to create one.");
                        }
                        else
                        {
                            this.WriteErrorDetails(ex);
                        }
                        return;
                    }

                    _createdDeployment = true;
                }
            }
            else
            {
                if (VNetName != null || DnsSettings != null)
                {
                    WriteWarning("VNetName or DnsSettings can only be specified on new deployments.");
                }
            }

            if (lastOperation != null && string.Compare(lastOperation.Status, OperationState.Failed, StringComparison.OrdinalIgnoreCase) == 0)
                return;

            // Only create the VM when a new VM was added and it was not created during the deployment phase.
            if ((_createdDeployment == false))
            {
                using (new OperationContextScope((IContextChannel)Channel))
                {
                    try
                    {
                        ExecuteClientAction(vm, CommandRuntime + " - Create VM " + vm.RoleName, s => this.Channel.AddRole(s, this.ServiceName, this.ServiceName, vm), WaitForOperation);
                    }
                    catch (CommunicationException ex)
                    {
                        this.WriteErrorDetails(ex);
                        return;
                    }
                }
            }
        }
Esempio n. 33
0
        private static ConnectionInfo FromUserSecrets(Func <string, IUserSecretsManager> userSecretsManagerFactory, Deployment options)
        {
            var secrets        = UserSecretsUtils.FromSecrets(userSecretsManagerFactory(options.ProjectPath));
            var secret         = secrets.First(profile => string.Equals(options.Profile.Name, profile.Name));
            var connectionInfo = new ConnectionInfo(options.Settings.Host, secret.Credentials.Username,
                                                    new PasswordAuthenticationMethod(secret.Credentials.Username, secret.Credentials.Password));

            return(connectionInfo);
        }
Esempio n. 34
0
 static Task <int> Main() => Deployment.RunAsync <WebServerStack>();
        /// <summary>
        /// Verify a deployment exists
        /// </summary>
        /// <param name="serviceName"></param>
        /// <param name="slot"></param>
        private void VerifyDeployment()
        {
            try
            {
                SafeWriteObjectWithTimestamp(Resources.PublishStartingMessage);
                SafeWriteObjectWithTimestamp(Resources.PublishInitializingMessage);

                Dictionary <string, RoleInstance> roleInstanceSnapshot = new Dictionary <string, RoleInstance>();

                // Continue polling for deployment until all of the roles
                // indicate they're ready
                Deployment deployment = new Deployment();
                do
                {
                    deployment = RetryCall(subscription =>
                                           Channel.GetDeploymentBySlot(
                                               subscription,
                                               _hostedServiceName,
                                               _deploymentSettings.ServiceSettings.Slot));

                    // The goal of this loop is to output a message whenever the status of a role
                    // instance CHANGES. To do that, we have to remember the last status of all role instances
                    // and that's what the roleInstanceSnapshot array is for
                    foreach (RoleInstance currentInstance in deployment.RoleInstanceList)
                    {
                        // We only care about these three statuses, ignore other intermediate statuses
                        if (String.Equals(currentInstance.InstanceStatus, RoleInstanceStatus.Busy) ||
                            String.Equals(currentInstance.InstanceStatus, RoleInstanceStatus.Ready) ||
                            String.Equals(currentInstance.InstanceStatus, RoleInstanceStatus.Initializing))
                        {
                            bool createdOrChanged = false;

                            // InstanceName is unique and concatenates the role name and instance name
                            if (roleInstanceSnapshot.ContainsKey(currentInstance.InstanceName))
                            {
                                // If we already have a snapshot of that role instance, update it
                                RoleInstance previousInstance = roleInstanceSnapshot[currentInstance.InstanceName];
                                if (!String.Equals(previousInstance.InstanceStatus, currentInstance.InstanceStatus))
                                {
                                    // If the instance status changed, we need to output a message
                                    previousInstance.InstanceStatus = currentInstance.InstanceStatus;
                                    createdOrChanged = true;
                                }
                            }
                            else
                            {
                                // If this is the first time we run through, we also need to output a message
                                roleInstanceSnapshot[currentInstance.InstanceName] = currentInstance;
                                createdOrChanged = true;
                            }


                            if (createdOrChanged)
                            {
                                string statusResource;
                                switch (currentInstance.InstanceStatus)
                                {
                                case RoleInstanceStatus.Busy:
                                    statusResource = Resources.PublishInstanceStatusBusy;
                                    break;

                                case RoleInstanceStatus.Ready:
                                    statusResource = Resources.PublishInstanceStatusReady;
                                    break;

                                default:
                                    statusResource = Resources.PublishInstanceStatusCreating;
                                    break;
                                }

                                SafeWriteObjectWithTimestamp(String.Format(Resources.PublishInstanceStatusMessage,
                                                                           currentInstance.InstanceName, currentInstance.RoleName, statusResource));
                            }
                        }
                    }

                    // If a deployment has many roles to initialize, this
                    // thread must throttle requests so the Azure portal
                    // doesn't reply with a "too many requests" error
                    Thread.Sleep(int.Parse(Resources.StandardRetryDelayInMs));
                }while (deployment.RoleInstanceList.Any(
                            r => r.InstanceStatus != RoleInstanceStatus.Ready));

                if (CanGenerateUrlForDeploymentSlot())
                {
                    SafeWriteObjectWithTimestamp(
                        Resources.PublishCreatedWebsiteMessage,
                        string.Format(Resources.ServiceUrl, _hostedServiceName));
                }
                else
                {
                    SafeWriteObjectWithTimestamp(
                        Resources.PublishCreatedWebsiteLaunchNotSupportedMessage);
                }
            }
            catch (EndpointNotFoundException)
            {
                throw new InvalidOperationException(
                          string.Format(
                              Resources.CannotFindDeployment,
                              _hostedServiceName,
                              _deploymentSettings.ServiceSettings.Slot));
            }
        }
Esempio n. 36
0
 private static Task <int> Main() => Deployment.RunAsync <GithubActionsWithAnAzureFunction>();
Esempio n. 37
0
 static Task <int> Main() => Deployment.RunAsync <MyAKS>();
Esempio n. 38
0
    static Task <int> Main(string[] args)
    {
        return(Deployment.RunAsync(() =>
        {
            // Minikube does not implement services of type `LoadBalancer`; require the user to
            // specify if we're running on minikube, and if so, create only services of type
            // ClusterIP.
            var config = new Config();
            var isMiniKube = config.GetBoolean("isMiniKube") ?? false;

            //
            // REDIS MASTER.
            //

            var redisMasterLabels = new InputMap <string> {
                { "app", "redis-master" },
            };

            var redisMasterDeployment = new Pulumi.Kubernetes.Apps.V1.Deployment("redis-master", new DeploymentArgs
            {
                Spec = new DeploymentSpecArgs
                {
                    Selector = new LabelSelectorArgs
                    {
                        MatchLabels = redisMasterLabels,
                    },
                    Template = new PodTemplateSpecArgs
                    {
                        Metadata = new ObjectMetaArgs
                        {
                            Labels = redisMasterLabels,
                        },
                        Spec = new PodSpecArgs
                        {
                            Containers =
                            {
                                new ContainerArgs
                                {
                                    Name = "master",
                                    Image = "k8s.gcr.io/redis:e2e",
                                    Resources = new ResourceRequirementsArgs
                                    {
                                        Requests =
                                        {
                                            { "cpu",    "100m"     },
                                            { "memory", "100Mi"    },
                                        },
                                    },
                                    Ports =
                                    {
                                        new ContainerPortArgs {
                                            ContainerPortValue = 6379
                                        }
                                    },
                                },
                            },
                        },
                    },
                },
            });

            var redisMasterService = new Pulumi.Kubernetes.Core.V1.Service("redis-master", new ServiceArgs
            {
                Metadata = new ObjectMetaArgs
                {
                    Name = "redis-master",
                    Labels = redisMasterDeployment.Metadata.Apply(metadata => metadata.Labels),
                },
                Spec = new ServiceSpecArgs
                {
                    Ports =
                    {
                        new ServicePortArgs
                        {
                            Port = 6379,
                            TargetPort = 6379,
                        },
                    },
                    Selector = redisMasterDeployment.Spec.Apply(spec => spec.Template.Metadata.Labels),
                }
            });

            //
            // REDIS REPLICA.
            //

            var redisReplicaLabels = new InputMap <string> {
                { "app", "redis-replica" },
            };

            var redisReplicaDeployment = new Pulumi.Kubernetes.Apps.V1.Deployment("redis-replica", new DeploymentArgs
            {
                Spec = new DeploymentSpecArgs
                {
                    Selector = new LabelSelectorArgs
                    {
                        MatchLabels = redisReplicaLabels,
                    },
                    Template = new PodTemplateSpecArgs
                    {
                        Metadata = new ObjectMetaArgs
                        {
                            Labels = redisReplicaLabels,
                        },
                        Spec = new PodSpecArgs
                        {
                            Containers =
                            {
                                new ContainerArgs
                                {
                                    Name = "replica",
                                    Image = "gcr.io/google_samples/gb-redisslave:v1",
                                    Resources = new ResourceRequirementsArgs
                                    {
                                        Requests =
                                        {
                                            { "cpu",    "100m"     },
                                            { "memory", "100Mi"    },
                                        },
                                    },
                                    // If your cluster config does not include a dns service, then to instead access an environment
                                    // variable to find the master service's host, change `value: "dns"` to read `value: "env"`.
                                    Env =
                                    {
                                        new EnvVarArgs
                                        {
                                            Name = "GET_HOSTS_FROM",
                                            Value = "dns"
                                        },
                                    },
                                    Ports =
                                    {
                                        new ContainerPortArgs {
                                            ContainerPortValue = 6379
                                        }
                                    },
                                },
                            },
                        },
                    },
                },
            });

            var redisReplicaService = new Pulumi.Kubernetes.Core.V1.Service("redis-replica", new ServiceArgs
            {
                Metadata = new ObjectMetaArgs
                {
                    Name = "redis-slave",
                    Labels = redisReplicaDeployment.Metadata.Apply(metadata => metadata.Labels),
                },
                Spec = new ServiceSpecArgs
                {
                    Ports =
                    {
                        new ServicePortArgs
                        {
                            Port = 6379,
                            TargetPort = 6379,
                        },
                    },
                    Selector = redisReplicaDeployment.Spec.Apply(spec => spec.Template.Metadata.Labels),
                }
            });

            //
            // FRONTEND
            //

            var frontendLabels = new InputMap <string> {
                { "app", "frontend" },
            };

            var frontendDeployment = new Pulumi.Kubernetes.Apps.V1.Deployment("frontend", new DeploymentArgs
            {
                Spec = new DeploymentSpecArgs
                {
                    Selector = new LabelSelectorArgs
                    {
                        MatchLabels = frontendLabels,
                    },
                    Replicas = 3,
                    Template = new PodTemplateSpecArgs
                    {
                        Metadata = new ObjectMetaArgs
                        {
                            Labels = frontendLabels,
                        },
                        Spec = new PodSpecArgs
                        {
                            Containers =
                            {
                                new ContainerArgs
                                {
                                    Name = "php-redis",
                                    Image = "gcr.io/google-samples/gb-frontend:v4",
                                    Resources = new ResourceRequirementsArgs
                                    {
                                        Requests =
                                        {
                                            { "cpu",    "100m"     },
                                            { "memory", "100Mi"    },
                                        },
                                    },
                                    // If your cluster config does not include a dns service, then to instead access an environment
                                    // variable to find the master service's host, change `value: "dns"` to read `value: "env"`.
                                    Env =
                                    {
                                        new EnvVarArgs
                                        {
                                            Name = "GET_HOSTS_FROM",
                                            Value = "dns", /* Value = "env"*/
                                        },
                                    },
                                    Ports =
                                    {
                                        new ContainerPortArgs {
                                            ContainerPortValue = 80
                                        }
                                    },
                                },
                            },
                        },
                    },
                },
            });

            var frontendService = new Pulumi.Kubernetes.Core.V1.Service("frontend", new ServiceArgs
            {
                Metadata = new ObjectMetaArgs
                {
                    Name = "frontend",
                    Labels = frontendDeployment.Metadata.Apply(metadata => metadata.Labels),
                },
                Spec = new ServiceSpecArgs
                {
                    Type = isMiniKube ? "ClusterIP" : "LoadBalancer",
                    Ports =
                    {
                        new ServicePortArgs
                        {
                            Port = 80,
                            TargetPort = 80,
                        },
                    },
                    Selector = frontendDeployment.Spec.Apply(spec => spec.Template.Metadata.Labels),
                }
            });

            Output <string> frontendIP;
            if (isMiniKube)
            {
                frontendIP = frontendService.Spec.Apply(spec => spec.ClusterIP);
            }
            else
            {
                frontendIP = frontendService.Status.Apply(status => status.LoadBalancer.Ingress[0].Hostname);
            }

            return new Dictionary <string, object> {
                { "frontendIp", frontendIP },
            };
        }));
    }
Esempio n. 39
0
        public DeploymentExtended ProvisionDeploymentStatus(string resourceGroup, string deploymentName, Deployment deployment)
        {
            operations = new List <DeploymentOperation>();

            return(WaitDeploymentStatus(
                       resourceGroup,
                       deploymentName,
                       deployment,
                       WriteDeploymentProgress,
                       ProvisioningState.Canceled,
                       ProvisioningState.Succeeded,
                       ProvisioningState.Failed));
        }
Esempio n. 40
0
        public void WhatIfAtSubscriptionScope_ModifyResources_ReturnsModifyChanges()
        {
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                // Arrange.
                ResourceManagementClient client = this.GetResourceManagementClient(context);

                var deployment = new Deployment
                {
                    Location   = "westus2",
                    Properties = new DeploymentProperties
                    {
                        Mode       = DeploymentMode.Incremental,
                        Template   = SubscriptionTemplate,
                        Parameters = JObject.Parse("{ 'storageAccountName': {'value': 'whatifnetsdktest1'}}"),
                    }
                };

                // Change "northeurope" to "westeurope".
                JObject newTemplate = JObject.Parse(SubscriptionTemplate);
                newTemplate["resources"][0]["properties"]["policyRule"]["if"]["equals"] = "westeurope";

                var deploymentWhatIf = new DeploymentWhatIf
                {
                    Location   = "westus2",
                    Properties = new DeploymentWhatIfProperties
                    {
                        Mode           = DeploymentMode.Incremental,
                        Template       = newTemplate,
                        Parameters     = JObject.Parse("{ 'storageAccountName': {'value': 'whatifnetsdktest1'}}"),
                        WhatIfSettings = new DeploymentWhatIfSettings(WhatIfResultFormat.FullResourcePayloads)
                    }
                };

                client.ResourceGroups.CreateOrUpdate("SDK-test", ResourceGroup);
                client.Deployments.CreateOrUpdateAtSubscriptionScope(NewDeploymentName(), deployment);

                // Act.
                WhatIfOperationResult result = client.Deployments
                                               .WhatIfAtSubscriptionScope(NewDeploymentName(), deploymentWhatIf);

                // Assert.
                Assert.Equal("Succeeded", result.Status);
                Assert.NotNull(result.Changes);
                Assert.NotEmpty(result.Changes);

                WhatIfChange policyChange = result.Changes.FirstOrDefault(change =>
                                                                          change.ResourceId.EndsWith("Microsoft.Authorization/policyDefinitions/policy2"));

                Assert.NotNull(policyChange);
                Assert.True(policyChange.ChangeType == ChangeType.Deploy ||
                            policyChange.ChangeType == ChangeType.Modify);
                Assert.NotNull(policyChange.Delta);
                Assert.NotEmpty(policyChange.Delta);

                WhatIfPropertyChange policyRuleChange = policyChange.Delta
                                                        .FirstOrDefault(propertyChange => propertyChange.Path.Equals("properties.policyRule.if.equals"));

                Assert.NotNull(policyRuleChange);
                Assert.Equal(PropertyChangeType.Modify, policyRuleChange.PropertyChangeType);
                Assert.Equal("northeurope", policyRuleChange.Before);
                Assert.Equal("westeurope", policyRuleChange.After);
            }
        }
Esempio n. 41
0
        private TemplateValidationInfo CheckBasicDeploymentErrors(string resourceGroup, string deploymentName, Deployment deployment)
        {
            DeploymentValidateResult validationResult = resourceGroup != null
                ? ResourceManagementClient.Deployments.Validate(resourceGroup, deploymentName, deployment)
                : ResourceManagementClient.Deployments.ValidateAtSubscriptionScope(deploymentName, deployment);

            return(new TemplateValidationInfo(validationResult));
        }
Esempio n. 42
0
 static Task <int> Main() => Deployment.RunAsync <NoraAzureStack>();
Esempio n. 43
0
 static Task <int> Main(string[] args) => Deployment.RunAsync <MyStack>();
        public void NoNameSpecifiedAndRoleInstanceListWithMultipleRoleInstanceWithSingleWinRMInputEndpointInDeployment()
        {
            var deployment = new Deployment
            {
                Url = deploymentUrl,
                RoleInstanceList = new RoleInstanceList
                {
                    new RoleInstance
                    {
                        InstanceEndpoints = new InstanceEndpointList
                        {
                            new InstanceEndpoint
                            {
                                LocalPort = WinRMConstants.HttpsListenerPort,
                                Name = WinRMConstants.EndpointName,
                                PublicPort = publicPort
                            }
                        }
                    },
                    new RoleInstance
                    {
                        InstanceEndpoints = new InstanceEndpointList
                        {
                            new InstanceEndpoint
                            {
                                LocalPort = WinRMConstants.HttpsListenerPort,
                                Name = WinRMConstants.EndpointName,
                                PublicPort = secondRolesPublicPort
                            }
                        }
                    }
                }
            };
            var winRmUri = new GetAzureWinRMUriStub(deployment)
            {
                CommandRuntime = mockCommandRuntime
            };
            winRmUri.ExecuteCommandBody();

            Assert.AreEqual(1, mockCommandRuntime.OutputPipeline.Count, "One item should be in the output pipeline");

            var uris = mockCommandRuntime.OutputPipeline[0] as List<Uri>;
            Assert.IsNotNull(uris, "List<Uri> is expected");

            var expectedUris = new List<Uri>
            {
                new UriBuilder("https", deploymentUrl.Host, publicPort).Uri,
                new UriBuilder("https", deploymentUrl.Host, secondRolesPublicPort).Uri
            };

            var a = (from e in expectedUris
                    where !uris.Contains(e)
                    select e).Count();

            Assert.IsTrue(a == 0, "Expected count: {0}, Found count:{1}", expectedUris.Count(), uris.Count());
        }
Esempio n. 45
0
        public void TestSetup()
        {
            GlobalPathInfo.GlobalSettingsDirectory      = Data.AzureSdkAppDir;
            CmdletSubscriptionExtensions.SessionManager = new InMemorySessionManager();

            storageService = new StorageService()
            {
                ServiceName        = storageName,
                StorageServiceKeys = new StorageServiceKeys()
                {
                    Primary   = "MNao3bm7t7B/x+g2/ssh9HnG0mEh1QV5EHpcna8CetYn+TSRoA8/SBoH6B3Ufwtnz3jZLSw9GEUuCTr3VooBWq==",
                    Secondary = "secondaryKey"
                },
                StorageServiceProperties = new StorageServiceProperties()
                {
                    Endpoints = new EndpointList()
                    {
                        "http://awesome.blob.core.windows.net/",
                        "http://awesome.queue.core.windows.net/",
                        "http://awesome.table.core.windows.net/"
                    }
                }
            };

            deployment = new Deployment()
            {
                DeploymentSlot   = DeploymentSlotType.Production,
                Name             = "mydeployment",
                PrivateID        = "privateId",
                Status           = DeploymentStatus.Starting,
                RoleInstanceList = new RoleInstanceList()
                {
                    new RoleInstance()
                    {
                        InstanceStatus = RoleInstanceStatus.ReadyRole,
                        RoleName       = "Role1",
                        InstanceName   = "Instance_Role1"
                    }
                }
            };

            cloudService = new HostedService()
            {
                ServiceName = serviceName,
                Deployments = new DeploymentList()
            };
            subscription = new SubscriptionData()
            {
                Certificate      = It.IsAny <X509Certificate2>(),
                IsDefault        = true,
                ServiceEndpoint  = "https://www.azure.com",
                SubscriptionId   = Guid.NewGuid().ToString(),
                SubscriptionName = Data.Subscription1
            };

            serviceManagementChannelMock = new Mock <IServiceManagement>();
            serviceManagementChannelMock.Setup(f => f.EndGetHostedServiceWithDetails(It.IsAny <IAsyncResult>()))
            .Returns(cloudService);
            serviceManagementChannelMock.Setup(f => f.EndGetStorageService((It.IsAny <IAsyncResult>())))
            .Returns(storageService);
            serviceManagementChannelMock.Setup(f => f.EndGetStorageKeys(It.IsAny <IAsyncResult>()))
            .Returns(storageService);
            serviceManagementChannelMock.Setup(f => f.EndGetDeploymentBySlot(It.IsAny <IAsyncResult>()))
            .Returns(deployment);

            cloudBlobUtilityMock = new Mock <CloudBlobUtility>();
            cloudBlobUtilityMock.Setup(f => f.UploadPackageToBlob(
                                           serviceManagementChannelMock.Object,
                                           It.IsAny <string>(),
                                           It.IsAny <string>(),
                                           It.IsAny <string>(),
                                           It.IsAny <BlobRequestOptions>())).Returns(new Uri("http://www.packageurl.azure.com"));

            client = new CloudServiceClient(subscription)
            {
                ServiceManagementChannel = serviceManagementChannelMock.Object,
                CloudBlobUtility         = cloudBlobUtilityMock.Object
            };
        }
Esempio n. 46
0
        public async Task DeploymentTestsTemplateAsJsonString()
        {
            List <string> dividedCases = new List <string> {
                (@"{
                '$schema': 'http://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#',
                'contentVersion': '1.0.0.0',
                'parameters': {
                    'storageAccountName': {
		                'value': 'tianotest04'
	                }
                }
            }").Replace("'", "\""),
                (@"{
                'storageAccountName': {
		            'value': 'tianotest04'
	            }
            }").Replace("'", "\"")
            };

            foreach (var parameterString in dividedCases)
            {
                var mockResponse = new MockResponse((int)HttpStatusCode.Created);
                var responseBody = (@"{
                    'id': 'foo',
                    'name': 'test-release-3',
                    'properties': {
                        'parameters': {
                            'storageAccountName': {
				                'type': 'String',
				                'value': 'tianotest04'
			                }
		                },
		                'mode': 'Incremental',
		                'provisioningState': 'Succeeded',
		                'timestamp': '2016-07-12T17:36:39.2398177Z',
		                'duration': 'PT0.5966357S',
		                'correlationId': 'c0d728d5-5b97-41b9-b79a-abcd9eb5fe4a'
	                }
                }").Replace("'", "\"");
                mockResponse.SetContent(responseBody);

                var templateString = (@"{
                    '$schema': 'http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#',
                    'contentVersion': '1.0.0.0',
                    'parameters': {
                        'storageAccountName': {
		                    'type': 'string'
	                    }
                    },
                    'resources': [
                    ],
                    'outputs': {  }
                }").Replace("'", "\"");

                JsonElement jsonParameter = JsonSerializer.Deserialize <JsonElement>(parameterString);
                if (!jsonParameter.TryGetProperty("parameters", out JsonElement parameter))
                {
                    parameter = jsonParameter;
                }
                var mockTransport = new MockTransport(mockResponse);
                var client        = GetResourceManagementClient(mockTransport);

                var parameters = new Deployment
                                 (
                    new DeploymentProperties(DeploymentMode.Incremental)
                {
                    Template       = templateString,
                    ParametersJson = parameter
                }
                                 );

                var raw = await client.Deployments.StartCreateOrUpdateAsync("foo", "myrealease-3.14", parameters);

                var result = (await WaitForCompletionAsync(raw)).Value;

                // Validate headers
                var request = mockTransport.Requests[0];
                Assert.IsTrue(request.Headers.Contains(new HttpHeader("Content-Type", "application/json")));
                Assert.AreEqual(HttpMethod.Put.Method, request.Method.Method);
                Assert.IsTrue(request.Headers.Contains("Authorization"));

                // Validate payload
                Stream stream = new MemoryStream();
                await request.Content.WriteToAsync(stream, default);

                stream.Position = 0;
                var resquestContent = new StreamReader(stream).ReadToEnd();
                var json            = JsonDocument.Parse(resquestContent).RootElement;
                Assert.AreEqual("Incremental", json.GetProperty("properties").GetProperty("mode").GetString());
                Assert.AreEqual("tianotest04", json.GetProperty("properties").GetProperty("parameters").GetProperty("storageAccountName").GetProperty("value").GetString());
                Assert.AreEqual("1.0.0.0", json.GetProperty("properties").GetProperty("template").GetProperty("contentVersion").GetString());

                // Validate result
                Assert.AreEqual("foo", result.Id);
                Assert.AreEqual("test-release-3", result.Name);
                Assert.AreEqual("Succeeded", result.Properties.ProvisioningState);
                Assert.AreEqual(DeploymentMode.Incremental, result.Properties.Mode);
                Assert.IsTrue(JsonSerializer.Serialize(result.Properties.Parameters).Contains("\"value\":\"tianotest04\""));
            }
        }
Esempio n. 47
0
 public static Task <int> Main() => Deployment.RunAsync <CCAClientStack>();
Esempio n. 48
0
        public async Task DeploymentTestsCreateValidateMessage()
        {
            var mockResponse = new MockResponse((int)HttpStatusCode.Created);
            var content      = @"{
                    'id': 'foo',
                    'name':'myrealease-3.14',
                    'properties':{
                        'provisioningState':'Succeeded',    
                        'timestamp':'2014-01-05T12:30:43.00Z',
                        'mode':'Incremental',
                        'template': { 'api-version' : '123' },
		                'templateLink': {
                           'uri': 'http://wa/template.json',
                           'contentVersion': '1.0.0.0',
                           'contentHash': {
                              'algorithm': 'sha256',
                              'value': 'yyz7xhhshfasf'
                           }
                        },
                        'parametersLink': {
                           'uri': 'http://wa/parameters.json',
                           'contentVersion': '1.0.0.0',
                           'contentHash': {
                              'algorithm': 'sha256',
                              'value': 'yyz7xhhshfasf'
                           }
                        },
                        'parameters': {
                            'key' : {
                                'type':'string',           
                                'value':'user'
                            }
		                },
                        'outputs': {
                            'key' : {
                                'type':'string',           
                                'value':'user'
                            }
                        }        
                    }
                }".Replace("'", "\"");

            mockResponse.SetContent(content);

            var dictionary = new Dictionary <string, object> {
                { "param1", "value1" },
                { "param2", true },
                { "param3", new Dictionary <string, object>()
                  {
                      { "param3_1", 123 },
                      { "param3_2", "value3_2" },
                  } }
            };
            var parameters = new Deployment
                             (
                new DeploymentProperties(DeploymentMode.Incremental)
            {
                Template     = "{\"api-version\": \"123\"}",
                TemplateLink = new TemplateLink("http://abc/def/template.json")
                {
                    ContentVersion = "1.0.0.0"
                },
                Parameters     = JsonSerializer.Serialize(dictionary),
                ParametersLink = new ParametersLink("http://abc/def/template.json")
                {
                    ContentVersion = "1.0.0.0"
                }
            }
                             );

            var mockTransport = new MockTransport(mockResponse);
            var client        = GetResourceManagementClient(mockTransport);

            DeploymentsCreateOrUpdateOperation raw = await client.Deployments.StartCreateOrUpdateAsync("foo", "myrealease-3.14", parameters);

            DeploymentExtended result = (await WaitForCompletionAsync(raw)).Value;

            // Validate headers
            var request = mockTransport.Requests[0];

            Assert.IsTrue(request.Headers.Contains(new HttpHeader("Content-Type", "application/json")));
            Assert.AreEqual(HttpMethod.Put.Method, request.Method.Method);
            Assert.IsTrue(request.Headers.Contains("Authorization"));

            // Validate payload
            Stream stream = new MemoryStream();
            await request.Content.WriteToAsync(stream, default);

            stream.Position = 0;
            var resquestContent = new StreamReader(stream).ReadToEnd();
            var json            = JsonDocument.Parse(resquestContent).RootElement;

            Assert.AreEqual("Incremental", json.GetProperty("properties").GetProperty("mode").GetString());
            Assert.AreEqual("http://abc/def/template.json", json.GetProperty("properties").GetProperty("templateLink").GetProperty("uri").GetString());
            Assert.AreEqual("1.0.0.0", json.GetProperty("properties").GetProperty("templateLink").GetProperty("contentVersion").GetString());
            Assert.AreEqual("1.0.0.0", json.GetProperty("properties").GetProperty("parametersLink").GetProperty("contentVersion").GetString());
            Assert.AreEqual("value1", json.GetProperty("properties").GetProperty("parameters").GetProperty("param1").GetString());
            Assert.True(json.GetProperty("properties").GetProperty("parameters").GetProperty("param2").GetBoolean());
            Assert.AreEqual(123, json.GetProperty("properties").GetProperty("parameters").GetProperty("param3").GetProperty("param3_1").GetInt32());
            Assert.AreEqual("value3_2", json.GetProperty("properties").GetProperty("parameters").GetProperty("param3").GetProperty("param3_2").GetString());
            Assert.AreEqual("123", json.GetProperty("properties").GetProperty("template").GetProperty("api-version").GetString());

            // Validate result
            Assert.AreEqual("foo", result.Id);
            Assert.AreEqual("myrealease-3.14", result.Name);
            Assert.AreEqual("Succeeded", result.Properties.ProvisioningState);
            Assert.AreEqual(new DateTimeOffset(2014, 1, 5, 12, 30, 43, new TimeSpan()), result.Properties.Timestamp);
            Assert.AreEqual(DeploymentMode.Incremental, result.Properties.Mode);
            Assert.AreEqual("http://wa/template.json", result.Properties.TemplateLink.Uri);
            Assert.AreEqual("1.0.0.0", result.Properties.TemplateLink.ContentVersion);
            Assert.IsTrue(JsonSerializer.Serialize(result.Properties.Parameters).Contains("\"type\":\"string\""));
            Assert.IsTrue(JsonSerializer.Serialize(result.Properties.Outputs).Contains("\"type\":\"string\""));
        }
Esempio n. 49
0
        public void WhatIf_ModifyResources_ReturnsModifyChanges()
        {
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                // Arrange.
                ResourceManagementClient client = this.GetResourceManagementClient(context);

                var deployment = new Deployment
                {
                    Properties = new DeploymentProperties
                    {
                        Mode       = DeploymentMode.Incremental,
                        Template   = ResourceGroupTemplate,
                        Parameters = ResourceGroupTemplateParameters,
                    }
                };

                // Modify account type: Standard_LRS => Standard_GRS.
                JObject newTemplate = JObject.Parse(ResourceGroupTemplate);
                newTemplate["resources"][0]["properties"]["accountType"] = "Standard_GRS";

                var deploymentWhatIf = new DeploymentWhatIf
                {
                    Properties = new DeploymentWhatIfProperties
                    {
                        Mode           = DeploymentMode.Incremental,
                        Template       = newTemplate,
                        Parameters     = ResourceGroupTemplateParameters,
                        WhatIfSettings = new DeploymentWhatIfSettings(WhatIfResultFormat.FullResourcePayloads)
                    }
                };

                string resourceGroupName = NewResourceGroupName();

                client.ResourceGroups.CreateOrUpdate(resourceGroupName, ResourceGroup);
                client.Deployments.CreateOrUpdate(resourceGroupName, NewDeploymentName(), deployment);

                // Act.
                WhatIfOperationResult result = client.Deployments
                                               .WhatIf(resourceGroupName, NewDeploymentName(), deploymentWhatIf);

                // Assert.
                Assert.Equal("Succeeded", result.Status);
                Assert.NotNull(result.Changes);
                Assert.NotEmpty(result.Changes);

                WhatIfChange storageAccountChange = result.Changes.FirstOrDefault(change =>
                                                                                  change.ResourceId.EndsWith("Microsoft.Storage/storageAccounts/tianotest102"));

                Assert.NotNull(storageAccountChange);
                Assert.Equal(ChangeType.Modify, storageAccountChange.ChangeType);

                Assert.NotNull(storageAccountChange.Delta);
                Assert.NotEmpty(storageAccountChange.Delta);

                WhatIfPropertyChange accountTypeChange = storageAccountChange.Delta
                                                         .FirstOrDefault(propertyChange => propertyChange.Path.Equals("properties.accountType"));

                Assert.NotNull(accountTypeChange);
                Assert.Equal("Standard_LRS", accountTypeChange.Before);
                Assert.Equal("Standard_GRS", accountTypeChange.After);
            }
        }
Esempio n. 50
0
        public async Task DeploymentTestsValidateCheckPayload()
        {
            var mockResponse = new MockResponse((int)HttpStatusCode.BadRequest);
            var content      = @"{
                      'error': {
                        'code': 'InvalidTemplate',
                        'message': 'Deployment template validation failed.'
                      }
                    }".Replace("'", "\"");

            mockResponse.SetContent(content);

            var dictionary = new Dictionary <string, object> {
                { "param1", "value1" },
                { "param2", true },
                { "param3", new Dictionary <string, object>()
                  {
                      { "param3_1", 123 },
                      { "param3_2", "value3_2" },
                  } }
            };
            var parameters = new Deployment
                             (
                new DeploymentProperties(DeploymentMode.Incremental)
            {
                TemplateLink = new TemplateLink("http://abc/def/template.json")
                {
                    ContentVersion = "1.0.0.0",
                },
                Parameters = JsonSerializer.Serialize(dictionary)
            }
                             );

            var mockTransport = new MockTransport(mockResponse);
            var client        = GetResourceManagementClient(mockTransport);

            try
            {
                var raw = await client.Deployments.StartValidateAsync("foo", "bar", parameters);

                var result = (await WaitForCompletionAsync(raw)).Value;
            }
            catch (RequestFailedException)
            {
                var    requestEX = mockTransport.Requests[0];
                Stream stream    = new MemoryStream();
                await requestEX.Content.WriteToAsync(stream, default);

                stream.Position = 0;
                var resquestContent = new StreamReader(stream).ReadToEnd();
                var json            = JsonDocument.Parse(resquestContent).RootElement;
                // Validate payload
                Assert.AreEqual("Incremental", json.GetProperty("properties").GetProperty("mode").GetString());
                Assert.AreEqual("http://abc/def/template.json", json.GetProperty("properties").GetProperty("templateLink").GetProperty("uri").GetString());
                Assert.AreEqual("1.0.0.0", json.GetProperty("properties").GetProperty("templateLink").GetProperty("contentVersion").GetString());
                Assert.AreEqual("value1", json.GetProperty("properties").GetProperty("parameters").GetProperty("param1").GetString());
                Assert.IsTrue(json.GetProperty("properties").GetProperty("parameters").GetProperty("param2").GetBoolean());
                Assert.AreEqual(123, json.GetProperty("properties").GetProperty("parameters").GetProperty("param3").GetProperty("param3_1").GetInt32());
                Assert.AreEqual("value3_2", json.GetProperty("properties").GetProperty("parameters").GetProperty("param3").GetProperty("param3_2").GetString());
            }

            // Validate headers
            var request = mockTransport.Requests[0];

            Assert.IsTrue(request.Headers.Contains(new HttpHeader("Content-Type", "application/json")));
            Assert.AreEqual(HttpMethod.Post.Method, request.Method.Method);
            Assert.IsTrue(request.Headers.Contains("Authorization"));
        }
Esempio n. 51
0
        public void Deploy(NetworkTopology networkTopology)
        {
            numberOfTTracer = Convert.ToInt32(Math.Round(percentageOfTunnelingTracer * networkTopology.Nodes.Count / 100, 0, MidpointRounding.AwayFromZero));
            numberOfMTracer = Convert.ToInt32(Math.Round(percentageOfMarkingTracer * networkTopology.Nodes.Count / 100, 0, MidpointRounding.AwayFromZero));
            numberOfFTracer = Convert.ToInt32(Math.Round(percentageOfFilteringTracer * networkTopology.Nodes.Count / 100, 0, MidpointRounding.AwayFromZero));

            List <int>        last_deploy_count;
            int               satisfy_count;
            Deployment        try_deploy = null;
            List <Deployment> dList      = new List <Deployment>();

            for (int K = 1; K <= networkTopology.Diameter; K++)
            {
                int N = 0;
                satisfy_count = 0;

                do
                {
                    if (try_deploy != null)
                    {
                        last_deploy_count = new List <int>(try_deploy.DeployNodes);
                    }
                    else
                    {
                        last_deploy_count = new List <int>();
                    }

                    try_deploy = Activator.CreateInstance(m_deploy_type, new object[] { percentageOfTunnelingTracer, percentageOfMarkingTracer, percentageOfFilteringTracer, K, ++N }) as Deployment;
                    try_deploy.Deploy(networkTopology);

                    if (try_deploy.DeployNodes.Count <= numberOfTTracer)
                    {
                        DataUtility.Log(string.Format("K={0},N={1},|D|={2}\n", try_deploy.K, try_deploy.N, try_deploy.DeployNodes.Count));
                        dList.Add(try_deploy);
                    }

                    if (try_deploy.DeployNodes.Except(last_deploy_count).Count() == 0 && last_deploy_count.Except(try_deploy.DeployNodes).Count() == 0)
                    {
                        satisfy_count++;
                    }
                    else
                    {
                        satisfy_count = 0;
                    }
                } while (satisfy_count < 2);
            }

            dList.Sort((x, y) => x.DeployNodes.Count.CompareTo(y.DeployNodes.Count));
            m_deployment = dList.Last();

            int c, e;
            List <NetworkTopology.Node> centerNode = new List <NetworkTopology.Node>();

            foreach (var scope in m_deployment.AllRoundScopeList)
            {
                if (scope.FindCenterNodeID(out c, out e, true))
                {
                    DataUtility.Log(string.Format("center ID: {0}\n", c));
                    centerNode.Add(networkTopology.Nodes.Find(n => n.ID == c));
                }
                else
                {
                    DataUtility.Log(string.Format("center ID: {0}\n", scope.Nodes[0].ID));
                    centerNode.Add(networkTopology.Nodes.Find(n => n.ID == scope.Nodes[0].ID));
                }
            }

            networkTopology.Reset();

            // Clear the deployment method.
            foreach (NetworkTopology.Node node in networkTopology.Nodes)
            {
                node.Tracer = NetworkTopology.TracerType.None;
            }

            centerNode.Sort((x, y) => x.Eccentricity.CompareTo(y.Eccentricity));

            m_deployment.FilteringTracerID = new List <int>();
            m_deployment.MarkingTracerID   = new List <int>();
            m_deployment.TunnelingTracerID = new List <int>();

            for (int i = 0; i < numberOfFTracer; i++)
            {
                NetworkTopology.Node node = centerNode.Find(n => n.Tracer == NetworkTopology.TracerType.None);
                if (node == null)
                {
                    int j = i;
                    do
                    {
                        NetworkTopology t = m_deployment.AllRoundScopeList.Find(s => s.Nodes.Exists(n => n == centerNode[j % centerNode.Count]));
                        node = t.Nodes.Find(n => n.Tracer == NetworkTopology.TracerType.None);
                        j++;
                    } while (node == null);
                }

                node.Tracer = NetworkTopology.TracerType.Filtering;
                m_deployment.FilteringTracerID.Add(node.ID);
            }

            for (int i = 0; i < numberOfMTracer; i++)
            {
                NetworkTopology.Node node = centerNode.Find(n => n.Tracer == NetworkTopology.TracerType.None);
                if (node == null)
                {
                    int j = i;
                    do
                    {
                        NetworkTopology t = m_deployment.AllRoundScopeList.Find(s => s.Nodes.Exists(n => n == centerNode[j % centerNode.Count]));
                        node = t.Nodes.Find(n => n.Tracer == NetworkTopology.TracerType.None);
                        j++;
                    } while (node == null);
                }

                node.Tracer = NetworkTopology.TracerType.Marking;
                m_deployment.MarkingTracerID.Add(node.ID);
            }

            foreach (int id in m_deployment.DeployNodes)
            {
                networkTopology.Nodes.Find(n => n.ID == id).Tracer = NetworkTopology.TracerType.Tunneling;
                m_deployment.TunnelingTracerID.Add(id);
            }

            if (m_deployment.DeployNodes.Count < numberOfTTracer)
            {
                for (int i = 0; i < numberOfTTracer - m_deployment.DeployNodes.Count; i++)
                {
                    NetworkTopology.Node node;
                    int j = i;
                    do
                    {
                        NetworkTopology t = m_deployment.AllRoundScopeList.Find(s => s.Nodes.Exists(n => n == centerNode[j % centerNode.Count]));
                        node = t.Nodes.Find(n => n.Tracer == NetworkTopology.TracerType.None);
                        j++;
                    } while (node == null);
                    node.Tracer = NetworkTopology.TracerType.Tunneling;
                    m_deployment.TunnelingTracerID.Add(node.ID);
                }
            }
        }
Esempio n. 52
0
 private static Task <int> Main()
 {
     return(Deployment.RunAsync(Logic));
 }
Esempio n. 53
0
 private DeploymentAction(ActionType actionType,
                          Deployment deployment = null)
 {
     this.actionType = actionType;
     this.deployment = deployment;
 }
Esempio n. 54
0
        public void NewAzureVMProcess()
        {
            SubscriptionData    currentSubscription = this.GetCurrentSubscription();
            CloudStorageAccount currentStorage      = null;

            try
            {
                currentStorage = currentSubscription.GetCurrentStorageAccount();
            }
            catch (ServiceManagementClientException) // couldn't access
            {
                throw new ArgumentException(Resources.CurrentStorageAccountIsNotAccessible);
            }
            if (currentStorage == null) // not set
            {
                throw new ArgumentException(Resources.CurrentStorageAccountIsNotSet);
            }

            bool serviceExists = DoesCloudServiceExist(this.ServiceName);

            if (!string.IsNullOrEmpty(this.Location))
            {
                if (serviceExists)
                {
                    throw new ApplicationException(Resources.ServiceExistsLocationCanNotBeSpecified);
                }
            }

            if (!string.IsNullOrEmpty(this.AffinityGroup))
            {
                if (serviceExists)
                {
                    throw new ApplicationException(Resources.ServiceExistsAffinityGroupCanNotBeSpecified);
                }
            }

            if (!serviceExists)
            {
                using (new OperationContextScope(Channel.ToContextChannel()))
                {
                    try
                    {
                        //Implicitly created hosted service2012-05-07 23:12

                        // Create the Cloud Service when
                        // Location or Affinity Group is Specified
                        // or VNET is specified and the service doesn't exist
                        var chsi = new CreateHostedServiceInput
                        {
                            AffinityGroup = this.AffinityGroup,
                            Location      = this.Location,
                            ServiceName   = this.ServiceName,
                            Description   = String.Format("Implicitly created hosted service{0}", DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd HH:mm")),
                            Label         = this.ServiceName
                        };

                        ExecuteClientAction(chsi, CommandRuntime + Resources.QuickVMCreateCloudService, s => this.Channel.CreateHostedService(s, chsi));
                    }

                    catch (ServiceManagementClientException ex)
                    {
                        this.WriteErrorDetails(ex);
                        return;
                    }
                }
            }

            if (ParameterSetName.Equals("Windows", StringComparison.OrdinalIgnoreCase))
            {
                if (WinRMCertificate != null)
                {
                    if (!CertUtils.HasExportablePrivateKey(WinRMCertificate))
                    {
                        throw new ArgumentException(Resources.WinRMCertificateDoesNotHaveExportablePrivateKey);
                    }
                    var operationDescription = string.Format(Resources.QuickVMUploadingWinRMCertificate, CommandRuntime, WinRMCertificate.Thumbprint);
                    var certificateFile      = CertUtils.Create(WinRMCertificate);
                    ExecuteClientActionInOCS(null, operationDescription, s => this.Channel.AddCertificates(s, this.ServiceName, certificateFile));
                }

                if (X509Certificates != null)
                {
                    var certificateFilesWithThumbprint = from c in X509Certificates
                                                         select new
                    {
                        c.Thumbprint,
                        CertificateFile = CertUtils.Create(c, this.NoExportPrivateKey.IsPresent)
                    };
                    foreach (var current in certificateFilesWithThumbprint.ToList())
                    {
                        var operationDescription = string.Format(Resources.QuickVMUploadingCertificate, CommandRuntime, current.Thumbprint);
                        ExecuteClientActionInOCS(null, operationDescription, s => this.Channel.AddCertificates(s, this.ServiceName, current.CertificateFile));
                    }
                }
            }

            var vm = CreatePersistenVMRole(currentStorage);

            // If the current deployment doesn't exist set it create it
            if (CurrentDeployment == null)
            {
                using (new OperationContextScope(Channel.ToContextChannel()))
                {
                    try
                    {
                        var deployment = new Deployment
                        {
                            DeploymentSlot = DeploymentSlotType.Production,
                            Name           = this.ServiceName,
                            Label          = this.ServiceName,
                            RoleList       = new RoleList {
                                vm
                            },
                            VirtualNetworkName = this.VNetName
                        };

                        if (this.DnsSettings != null)
                        {
                            deployment.Dns = new DnsSettings {
                                DnsServers = new DnsServerList()
                            };
                            foreach (DnsServer dns in this.DnsSettings)
                            {
                                deployment.Dns.DnsServers.Add(dns);
                            }
                        }

                        var operationDescription = string.Format(Resources.QuickVMCreateDeploymentWithVM, CommandRuntime, vm.RoleName);
                        ExecuteClientAction(deployment, operationDescription, s => this.Channel.CreateDeployment(s, this.ServiceName, deployment));

                        if (WaitForBoot.IsPresent)
                        {
                            WaitForRoleToBoot(vm.RoleName);
                        }
                    }

                    catch (ServiceManagementClientException ex)
                    {
                        if (ex.HttpStatus == HttpStatusCode.NotFound)
                        {
                            throw new Exception(Resources.ServiceDoesNotExistSpecifyLocationOrAffinityGroup);
                        }
                        else
                        {
                            this.WriteErrorDetails(ex);
                        }
                        return;
                    }

                    _createdDeployment = true;
                }
            }
            else
            {
                if (VNetName != null || DnsSettings != null)
                {
                    WriteWarning(Resources.VNetNameOrDnsSettingsCanOnlyBeSpecifiedOnNewDeployments);
                }
            }


            // Only create the VM when a new VM was added and it was not created during the deployment phase.
            if ((_createdDeployment == false))
            {
                using (new OperationContextScope(Channel.ToContextChannel()))
                {
                    try
                    {
                        var operationDescription = string.Format(Resources.QuickVMCreateVM, CommandRuntime, vm.RoleName);
                        ExecuteClientAction(vm, operationDescription, s => this.Channel.AddRole(s, this.ServiceName, this.ServiceName, vm));
                        if (WaitForBoot.IsPresent)
                        {
                            WaitForRoleToBoot(vm.RoleName);
                        }
                    }
                    catch (ServiceManagementClientException ex)
                    {
                        this.WriteErrorDetails(ex);
                        return;
                    }
                }
            }
        }
Esempio n. 55
0
 public static DeploymentAction NewStopAction(Deployment deployment)
 {
     return(new DeploymentAction(ActionType.Stop, deployment));
 }
        /// <summary>
        /// Deploys an ARM template at resource group level
        /// </summary>
        /// <param name="resourceGroupName">The resource group name</param>
        /// <param name="deploymentName">The deployment name</param>
        /// <param name="deployment">The deployment</param>
        public void DeployArmTemplate(string resourceGroupName, string deploymentName, Deployment deployment)
        {
            GetCurrentResourcesClient(Context).Deployments.BeginCreateOrUpdate(resourceGroupName, deploymentName, deployment);

            WaitForDeployment(resourceGroupName, deploymentName);
        }
Esempio n. 57
0
        private string GetDeploymentId(PublishContext context)
        {
            Deployment deployment = new Deployment();

            do
            {
                // If a deployment has many roles to initialize, this
                // thread must throttle requests so the Azure portal
                // doesn't reply with a "too many requests" error
                Thread.Sleep(SleepDuration);

                try
                {
                    deployment = ServiceManagementChannel.GetDeploymentBySlot(
                        subscriptionId,
                        context.ServiceName,
                        context.ServiceSettings.Slot);
                }
                catch (Exception e)
                {
                    if (e.Message != Resources.InternalServerErrorMessage)
                    {
                        throw;
                    }
                }
            }
            while (deployment.Status != DeploymentStatus.Starting && deployment.Status != DeploymentStatus.Running);

            return deployment.PrivateID;
        }
        public string GetStatus(string serviceName, string slot)
        {
            Deployment deployment = new Deployment();

            try
            {
                InvokeInOperationContext(() =>
                {
                    deployment = this.RetryCall<Deployment>(s => this.Channel.GetDeploymentBySlot(s, serviceName, slot));
                });
            }
            catch (ServiceManagementClientException ex)
            {
                if(ex.HttpStatus == HttpStatusCode.NotFound)
                {
                    throw new EndpointNotFoundException(string.Format(Resources.ServiceSlotDoesNotExist, slot, serviceName));
                }
            }

            return deployment.Status;
        }
Esempio n. 59
0
        public void Deploy(Deployment deployment)
        {
            var existingDeployment = _deploymentInstances.SingleOrDefault(x => x.DeploymentId == deployment.Id);
            if (existingDeployment != null)
            {
                if (existingDeployment.RollbackCompleted) // Deployment have been rolled back by other server  already.
                {
                    return;
                }

                _deploymentInstances.RemoveAll(x => x.DeploymentId == deployment.Id);
            }

            var sw = new Stopwatch();
            var fullSw = new Stopwatch();

            fullSw.Start();
            SendResponse(deployment.Id, DeploymentResponseType.DeploymentRequestReceived,  "Received deployment request.");
            IisSite site = SiteManager.GetSiteByName(deployment.SiteName);
            var originalPath = site.SitePath;

            var rootPath = site.SitePath;
            var directoryName = new DirectoryInfo(rootPath).Name;

            if (directoryName.StartsWith("servant-"))
            {
                rootPath = rootPath.Substring(0, rootPath.LastIndexOf(@"\", System.StringComparison.Ordinal));
            }
            var newPath = Path.Combine(rootPath, "servant-" + deployment.Guid);

            var fullPath = Environment.ExpandEnvironmentVariables(newPath);
            Directory.CreateDirectory(fullPath);
            SendResponse(deployment.Id, DeploymentResponseType.CreateDirectory, "Created directory: " + fullPath);

            sw.Start();
            var zipFile = DownloadUrl(deployment.Url);
            sw.Stop();
            SendResponse(deployment.Id, DeploymentResponseType.PackageDownload, string.Format("Completed package download in {0} seconds.", sw.Elapsed.TotalSeconds));

            var fastZip = new FastZip();
            var stream = new MemoryStream(zipFile);
            fastZip.ExtractZip(stream, fullPath, FastZip.Overwrite.Always, null, null, null, true, true);
            SendResponse(deployment.Id, DeploymentResponseType.PackageUnzipping, "Completed package extracting.");

            site.SitePath = newPath;
            SiteManager.UpdateSite(site);
            if (site.ApplicationPoolState == InstanceState.Started)
            {
                SiteManager.RecycleApplicationPool(site.ApplicationPool);
            }
            fullSw.Stop();

            SendResponse(deployment.Id, DeploymentResponseType.ChangeSitePath, string.Format("Changed site path to {0}. Deployment completed in {1} seconds.", fullPath, fullSw.Elapsed.TotalSeconds));

            var rollbackCompleted = false;
            if (deployment.WarmupAfterDeploy)
            {
                System.Threading.Thread.Sleep(1000); // Waits for IIS to complete
                var warmupResult = Warmup(site, deployment.WarmupUrl);
                SendResponse(deployment.Id, DeploymentResponseType.WarmupResult, Json.SerializeToString(warmupResult));
                var msg = warmupResult == null ? "Could not contact IIS site" : string.Format("Site locally returned HTTP {0} {1}.", (int) warmupResult.StatusCode, warmupResult.StatusCode);

                SendResponse(deployment.Id, DeploymentResponseType.Warmup, msg, warmupResult.StatusCode == HttpStatusCode.OK);

                if (deployment.RollbackOnError)
                {
                    // Roll-back if not 200 OK
                    if (warmupResult.StatusCode != HttpStatusCode.OK)
                    {
                        site.SitePath = originalPath;
                        SiteManager.UpdateSite(site);
                        if (site.ApplicationPoolState == InstanceState.Started)
                        {
                            SiteManager.RecycleApplicationPool(site.ApplicationPool);
                        }
                        rollbackCompleted = true;
                        Warmup(site, deployment.WarmupUrl);

                        SendResponse(deployment.Id, DeploymentResponseType.Rollback, string.Format("Rollback completed. Site path is now: {0}.", originalPath));
                    }
                }
            }

            _deploymentInstances.Add(new DeploymentInstance() { DeploymentId = deployment.Id, DeploymentGuid = deployment.Guid, NewPath = newPath, OriginalPath = originalPath, RollbackCompleted = rollbackCompleted, IisSiteId = site.IisId });
        }
Esempio n. 60
0
 private IActionResult CreateRedirect(Deployment deployment)
 {
     return(View("CreateRedirect", _handler.GenerateWebhookParams(deployment)));
 }