protected PSArgument[] CreateDeploymentUpgradeByNameParameters()
        {
            string serviceName    = string.Empty;
            string deploymentName = string.Empty;
            DeploymentUpgradeParameters parameters = new DeploymentUpgradeParameters();

            return(ConvertFromObjectsToArguments(new string[] { "ServiceName", "DeploymentName", "Parameters" }, new object[] { serviceName, deploymentName, parameters }));
        }
        protected void ExecuteDeploymentUpgradeByNameMethod(object[] invokeMethodInputParameters)
        {
            string serviceName    = (string)ParseParameter(invokeMethodInputParameters[0]);
            string deploymentName = (string)ParseParameter(invokeMethodInputParameters[1]);
            DeploymentUpgradeParameters parameters = (DeploymentUpgradeParameters)ParseParameter(invokeMethodInputParameters[2]);

            var result = DeploymentClient.UpgradeByName(serviceName, deploymentName, parameters);

            WriteObject(result);
        }
Esempio n. 3
0
        private void UpgradeDeployment(PublishContext context)
        {
            var upgradeParams = new DeploymentUpgradeParameters
            {
                Configuration = General.GetConfiguration(context.ConfigPath),
                PackageUri    = UploadPackage(context),
                Label         = context.ServiceName,
                Mode          = DeploymentUpgradeMode.Auto
            };

            WriteVerboseWithTimestamp(Resources.PublishUpgradingMessage);

            var uploadedCertificates = ComputeClient.ServiceCertificates.List(context.ServiceName);

            AddCertificates(uploadedCertificates, context);

            ComputeClient.Deployments.UpgradeBySlot(context.ServiceName, GetSlot(context.ServiceSettings.Slot), upgradeParams);
        }
        public static async Task DeployAsync(string source, SubscriptionListOperationResponse.Subscription subscription, HostedServiceListResponse.HostedService service,
                                             StorageAccount storage, DeploymentSlot slot, UpgradePreference upgradePreference, string pathToCspkg,
                                             string pathToCscfg, string pathToDiagExtensionConfig, StorageAccount diagStorage, string deploymentLabel,
                                             bool cleanupUnusedExtensions, bool forceWhenUpgrading)
        {
            Logger.InfoFormat("[" + source + "] " + "Preparing for deployment of {0}...", service.ServiceName);
            var credentials   = GetCredentials(source, subscription);
            var computeClient = new ComputeManagementClient(credentials);
            var storageClient = new StorageManagementClient(credentials);

            // Load csdef
            var csCfg = File.ReadAllText(pathToCscfg);

            // Load diag config
            var diagConfig = pathToDiagExtensionConfig != null?File.ReadAllText(pathToDiagExtensionConfig) : null;

            // Upgrade cspkg to storage
            Logger.InfoFormat("[" + source + "] " + "Fetching key for storage account {0}...", storage.Name);
            var keys = await storageClient.StorageAccounts.GetKeysAsync(storage.Name);

            var csa          = new CloudStorageAccount(new StorageCredentials(storage.Name, keys.PrimaryKey), true);
            var blobClient   = csa.CreateCloudBlobClient();
            var containerRef = blobClient.GetContainerReference("acd-deployments");

            if (!await containerRef.ExistsAsync())
            {
                Logger.InfoFormat("[" + source + "] " + "Creating container {0}...", containerRef.Name);
                await containerRef.CreateIfNotExistsAsync();
            }
            var filename = service.ServiceName + "-" + slot.ToString() + ".cspkg";

            var blobRef = containerRef.GetBlockBlobReference(filename);

            Logger.InfoFormat("[" + source + "] " + "Uploading package to {0}...", blobRef.Uri);
            await blobRef.UploadFromFileAsync(pathToCspkg, FileMode.Open);

            // Private diagnostics config
            string diagStorageName = null, diagStorageKey = null;

            if (diagStorage == null)
            {
                Logger.InfoFormat("[" + source + "] " + "Using storage account credentials from .cscfg for diagnostics...");
                Regex regex = new Regex("Diagnostics.ConnectionString.*?DefaultEndpointsProtocol.*?AccountName=(.+?);.*?AccountKey=([a-zA-Z0-9/+=]+)", RegexOptions.Singleline);
                Match m     = regex.Match(csCfg);
                if (m.Success)
                {
                    diagStorageName = m.Groups[1].Value;
                    diagStorageKey  = m.Groups[2].Value;
                    Logger.InfoFormat("[" + source + "] " + "Extracted storage account {0} from .cscfg for diagnostics...", diagStorageName);
                }
                else
                {
                    throw new ApplicationException("Couldn't extract Diagnostics ConnectionString from .cscfg");
                }
            }
            else
            {
                Logger.InfoFormat("[" + source + "] " + "Using storage account {0} for diagnostics...", diagStorage.Name);
                if (storage.Name == diagStorage.Name)
                {
                    diagStorageName = diagStorage.Name;
                    diagStorageKey  = keys.PrimaryKey;
                }
                else
                {
                    Logger.InfoFormat("[" + source + "] " + "Fetching keys for storage account {0}...", diagStorage.Name);
                    var diagKeys = await storageClient.StorageAccounts.GetKeysAsync(diagStorage.Name);

                    diagStorageName = diagStorage.Name;
                    diagStorageKey  = diagKeys.PrimaryKey;
                }
            }
            var privateDiagConfig = string.Format(@"<PrivateConfig xmlns=""http://schemas.microsoft.com/ServiceHosting/2010/10/DiagnosticsConfiguration"">
    <StorageAccount name=""{0}"" key=""{1}"" />
  </PrivateConfig>", diagStorageName, diagStorageKey);

            // Get diagnostics extension template
            Logger.InfoFormat("[" + source + "] " + "Retrieving available extensions...");
            var availableExtensions = await computeClient.HostedServices.ListAvailableExtensionsAsync();

            var availableDiagnosticsExtension = availableExtensions.Where(d => d.Type == "PaaSDiagnostics").First();

            // Cleanup of existing extensions
            if (cleanupUnusedExtensions)
            {
                await CleanupExistingExtensions(source, subscription, service, computeClient, availableDiagnosticsExtension);
            }
            else
            {
                Logger.InfoFormat("[" + source + "] " + "Skip cleaning unused extensions as configured");
            }

            // Extensions config
            var extensionConfiguration = new ExtensionConfiguration();

            // Create the extension with new configuration
            if (diagConfig != null)
            {
                var diagnosticsId = "acd-diagnostics-" + Guid.NewGuid().ToString("N");
                Logger.InfoFormat("[" + source + "] " + "Adding new diagnostics extension {0}...", diagnosticsId);
                var createExtensionOperation = await computeClient.HostedServices.BeginAddingExtensionAsync(service.ServiceName, new HostedServiceAddExtensionParameters()
                {
                    ProviderNamespace = availableDiagnosticsExtension.ProviderNameSpace,
                    Type                 = availableDiagnosticsExtension.Type,
                    Id                   = diagnosticsId,
                    Version              = availableDiagnosticsExtension.Version,
                    PublicConfiguration  = diagConfig,
                    PrivateConfiguration = privateDiagConfig
                });
                await WaitForOperationAsync(source, subscription, computeClient, createExtensionOperation.RequestId);

                // Extension configuration
                extensionConfiguration.AllRoles.Add(new ExtensionConfiguration.Extension
                {
                    Id = diagnosticsId
                });
            }

            // Create deployment parameters
            var deployParams = new DeploymentCreateParameters
            {
                StartDeployment        = true,
                Name                   = Guid.NewGuid().ToString("N"),
                Configuration          = csCfg,
                PackageUri             = blobRef.Uri,
                Label                  = deploymentLabel ?? DateTime.UtcNow.ToString("u") + " " + Environment.UserName,
                ExtensionConfiguration = extensionConfiguration
            };
            var upgradeParams = new DeploymentUpgradeParameters
            {
                Configuration          = csCfg,
                PackageUri             = blobRef.Uri,
                Label                  = deploymentLabel ?? DateTime.UtcNow.ToString("u") + " " + Environment.UserName,
                ExtensionConfiguration = extensionConfiguration,
                Mode  = upgradePreference == UpgradePreference.UpgradeSimultaneously ? DeploymentUpgradeMode.Simultaneous : DeploymentUpgradeMode.Auto,
                Force = forceWhenUpgrading
            };

            Logger.InfoFormat("[" + source + "] " + "Label for deployment: {0}", deployParams.Label);

            switch (upgradePreference)
            {
            case UpgradePreference.DeleteAndCreateDeploymentInitiallyStopped:
            case UpgradePreference.DeleteAndCreateDeployment:
            {
                // In the case of initially stopped, set StartDeployment to false (we default to 'true' above)
                if (upgradePreference == UpgradePreference.DeleteAndCreateDeploymentInitiallyStopped)
                {
                    deployParams.StartDeployment = false;
                }

                // Is there a deployment in this slot?
                Logger.InfoFormat("[" + source + "] " + "Fetching detailed service information...");
                var detailedService = await computeClient.HostedServices.GetDetailedAsync(service.ServiceName);

                var currentDeployment = detailedService.Deployments.Where(s => s.DeploymentSlot == slot).FirstOrDefault();
                if (currentDeployment != null)
                {
                    // Yes, there is. Save the deployment name for the recreate. This is to increase compatibility with
                    // cloud service monitoring tools.
                    deployParams.Name = currentDeployment.Name;

                    // Delete it.
                    Logger.InfoFormat("[" + source + "] " + "Deployment in {0} slot exists, deleting...", slot);
                    var deleteOperation = await computeClient.Deployments.BeginDeletingBySlotAsync(service.ServiceName, slot);
                    await WaitForOperationAsync(source, subscription, computeClient, deleteOperation.RequestId);
                }

                // Create a new deployment in this slot
                Logger.InfoFormat("[" + source + "] " + "Creating deployment in {0} slot...", slot);
                var createOperation = await computeClient.Deployments.BeginCreatingAsync(service.ServiceName, slot, deployParams);
                await WaitForOperationAsync(source, subscription, computeClient, createOperation.RequestId);
            }

            break;

            case UpgradePreference.UpgradeWithUpdateDomains:
            case UpgradePreference.UpgradeSimultaneously:
            {
                // Is there a deployment in this slot?
                Logger.InfoFormat("[" + source + "] " + "Fetching detailed service information...");
                var detailedService = await computeClient.HostedServices.GetDetailedAsync(service.ServiceName);

                var currentDeployment = detailedService.Deployments.Where(s => s.DeploymentSlot == slot).FirstOrDefault();
                if (currentDeployment != null)
                {
                    // Yes, there is. Upgrade it.
                    Logger.InfoFormat("[" + source + "] " + "Deployment in {0} slot exists, upgrading...", slot);
                    var upgradeOperation = await computeClient.Deployments.BeginUpgradingBySlotAsync(service.ServiceName, slot, upgradeParams);
                    await WaitForOperationAsync(source, subscription, computeClient, upgradeOperation.RequestId);
                }
                else
                {
                    // No, there isn't. Create.
                    Logger.InfoFormat("[" + source + "] " + "No deployment in {0} slot yet, creating...", slot);
                    var createOperation = await computeClient.Deployments.BeginCreatingAsync(service.ServiceName, slot, deployParams);
                    await WaitForOperationAsync(source, subscription, computeClient, createOperation.RequestId);
                }
            }

            break;
            }

            Logger.InfoFormat("[" + source + "] " + "Deployment succesful");
        }
        public void ExecuteCommand()
        {
            string configString = string.Empty;

            if (!string.IsNullOrEmpty(Configuration))
            {
                configString = GeneralUtilities.GetConfiguration(Configuration);
            }

            ExtensionConfiguration extConfig = null;

            if (ExtensionConfiguration != null)
            {
                string errorConfigInput = null;
                if (!ExtensionManager.Validate(ExtensionConfiguration, out errorConfigInput))
                {
                    throw new Exception(string.Format(Resources.ServiceExtensionCannotApplyExtensionsInSameType, errorConfigInput));
                }

                foreach (ExtensionConfigurationInput context in ExtensionConfiguration)
                {
                    if (context != null && context.X509Certificate != null)
                    {
                        ExecuteClientActionNewSM(
                            null,
                            string.Format(Resources.ServiceExtensionUploadingCertificate, CommandRuntime, context.X509Certificate.Thumbprint),
                            () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, CertUtilsNewSM.Create(context.X509Certificate)));
                    }
                }

                var slotType            = (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true);
                DeploymentGetResponse d = null;
                InvokeInOperationContext(() =>
                {
                    try
                    {
                        d = this.ComputeClient.Deployments.GetBySlot(this.ServiceName, slotType);
                    }
                    catch (CloudException ex)
                    {
                        if (ex.Response.StatusCode != HttpStatusCode.NotFound && IsVerbose() == false)
                        {
                            this.WriteExceptionDetails(ex);
                        }
                    }
                });

                ExtensionManager extensionMgr = new ExtensionManager(this, ServiceName);
                extConfig = extensionMgr.Add(d, ExtensionConfiguration, this.Slot);
            }

            // Upgrade Parameter Set
            if (string.Compare(ParameterSetName, "Upgrade", StringComparison.OrdinalIgnoreCase) == 0)
            {
                bool removePackage = false;
                var  storageName   = Profile.Context.Subscription.GetProperty(AzureSubscription.Property.StorageAccount);

                Uri packageUrl = null;
                if (Package.StartsWith(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) ||
                    Package.StartsWith(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase))
                {
                    packageUrl = new Uri(Package);
                }
                else
                {
                    if (string.IsNullOrEmpty(storageName))
                    {
                        throw new ArgumentException(Resources.CurrentStorageAccountIsNotSet);
                    }

                    var progress = new ProgressRecord(0, Resources.WaitForUploadingPackage, Resources.UploadingPackage);
                    WriteProgress(progress);
                    removePackage = true;
                    InvokeInOperationContext(() => packageUrl = RetryCall(s => AzureBlob.UploadPackageToBlob(this.StorageClient, storageName, Package, null)));
                }

                DeploymentUpgradeMode upgradeMode;
                if (!Enum.TryParse <DeploymentUpgradeMode>(Mode, out upgradeMode))
                {
                    upgradeMode = DeploymentUpgradeMode.Auto;
                }

                var upgradeDeploymentInput = new DeploymentUpgradeParameters
                {
                    Mode                   = upgradeMode,
                    Configuration          = configString,
                    ExtensionConfiguration = extConfig,
                    PackageUri             = packageUrl,
                    Label                  = Label ?? ServiceName,
                    Force                  = Force.IsPresent
                };

                if (!string.IsNullOrEmpty(RoleName))
                {
                    upgradeDeploymentInput.RoleToUpgrade = RoleName;
                }

                InvokeInOperationContext(() =>
                {
                    try
                    {
                        ExecuteClientActionNewSM(
                            upgradeDeploymentInput,
                            CommandRuntime.ToString(),
                            () => this.ComputeClient.Deployments.UpgradeBySlot(
                                this.ServiceName,
                                (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true),
                                upgradeDeploymentInput));

                        if (removePackage == true)
                        {
                            this.RetryCall(s =>
                                           AzureBlob.DeletePackageFromBlob(
                                               this.StorageClient,
                                               storageName,
                                               packageUrl));
                        }
                    }
                    catch (CloudException ex)
                    {
                        this.WriteExceptionDetails(ex);
                    }
                });
            }
            else if (string.Compare(this.ParameterSetName, "Config", StringComparison.OrdinalIgnoreCase) == 0)
            {
                // Config parameter set
                var changeDeploymentStatusParams = new DeploymentChangeConfigurationParameters
                {
                    Configuration          = configString,
                    ExtensionConfiguration = extConfig
                };

                ExecuteClientActionNewSM(
                    changeDeploymentStatusParams,
                    CommandRuntime.ToString(),
                    () => this.ComputeClient.Deployments.ChangeConfigurationBySlot(
                        this.ServiceName,
                        (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true),
                        changeDeploymentStatusParams));
            }
            else
            {
                // Status parameter set
                var updateDeploymentStatusParams = new DeploymentUpdateStatusParameters
                {
                    Status = (UpdatedDeploymentStatus)Enum.Parse(typeof(UpdatedDeploymentStatus), this.NewStatus, true)
                };

                ExecuteClientActionNewSM(
                    null,
                    CommandRuntime.ToString(),
                    () => this.ComputeClient.Deployments.UpdateStatusByDeploymentSlot(
                        this.ServiceName,
                        (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true),
                        updateDeploymentStatusParams));
            }
        }
        private void UpgradeDeployment(PublishContext context)
        {
            var upgradeParams = new DeploymentUpgradeParameters
            {
                Configuration = General.GetConfiguration(context.ConfigPath),
                PackageUri = UploadPackage(context),
                Label = context.ServiceName,
                Mode = DeploymentUpgradeMode.Auto
            };

            WriteVerboseWithTimestamp(Resources.PublishUpgradingMessage);

            var uploadedCertificates = ComputeClient.ServiceCertificates.List(context.ServiceName);
            AddCertificates(uploadedCertificates, context);

            ComputeClient.Deployments.UpgradeBySlot(context.ServiceName, GetSlot(context.ServiceSettings.Slot), upgradeParams);
        }
        public void ExecuteCommand()
        {
            string configString = string.Empty;
            if (!string.IsNullOrEmpty(Configuration))
            {
                configString = GeneralUtilities.GetConfiguration(Configuration);
            }

            ExtensionConfiguration extConfig = null;
            if (ExtensionConfiguration != null)
            {
                string errorConfigInput = null;
                if (!ExtensionManager.Validate(ExtensionConfiguration, out errorConfigInput))
                {
                    throw new Exception(string.Format(Resources.ServiceExtensionCannotApplyExtensionsInSameType, errorConfigInput));
                }

                foreach (ExtensionConfigurationInput context in ExtensionConfiguration)
                {
                    if (context != null && context.X509Certificate != null)
                    {
                        ExecuteClientActionNewSM(
                            null,
                            string.Format(Resources.ServiceExtensionUploadingCertificate, CommandRuntime, context.X509Certificate.Thumbprint),
                            () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, CertUtilsNewSM.Create(context.X509Certificate)));
                    }
                }

                var slotType = (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true);
                DeploymentGetResponse d = null;
                InvokeInOperationContext(() =>
                {
                    try
                    {
                        d = this.ComputeClient.Deployments.GetBySlot(this.ServiceName, slotType);
                    }
                    catch (CloudException ex)
                    {
                        if (ex.Response.StatusCode != HttpStatusCode.NotFound && IsVerbose() == false)
                        {
                            this.WriteExceptionDetails(ex);
                        }
                    }
                });

                ExtensionManager extensionMgr = new ExtensionManager(this, ServiceName);
                extConfig = extensionMgr.Add(d, ExtensionConfiguration, this.Slot);
            }

            // Upgrade Parameter Set
            if (string.Compare(ParameterSetName, "Upgrade", StringComparison.OrdinalIgnoreCase) == 0)
            {
                bool removePackage = false;
                var storageName = CurrentSubscription.CurrentStorageAccountName;

                Uri packageUrl = null;
                if (Package.StartsWith(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) ||
                    Package.StartsWith(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase))
                {
                    packageUrl = new Uri(Package);
                }
                else
                {
                    if (string.IsNullOrEmpty(storageName))
                    {
                        throw new ArgumentException(Resources.CurrentStorageAccountIsNotSet);
                    }

                    var progress = new ProgressRecord(0, Resources.WaitForUploadingPackage, Resources.UploadingPackage);
                    WriteProgress(progress);
                    removePackage = true;
                    InvokeInOperationContext(() => packageUrl = RetryCall(s => AzureBlob.UploadPackageToBlob(this.StorageClient, storageName, Package, null)));
                }

                DeploymentUpgradeMode upgradeMode;
                if (!Enum.TryParse<DeploymentUpgradeMode>(Mode, out upgradeMode))
                {
                    upgradeMode = DeploymentUpgradeMode.Auto;
                }

                var upgradeDeploymentInput = new DeploymentUpgradeParameters
                {
                    Mode = upgradeMode,
                    Configuration = configString,
                    ExtensionConfiguration = extConfig,
                    PackageUri = packageUrl,
                    Label = Label ?? ServiceName,
                    Force = Force.IsPresent
                };

                if (!string.IsNullOrEmpty(RoleName))
                {
                    upgradeDeploymentInput.RoleToUpgrade = RoleName;
                }

                InvokeInOperationContext(() =>
                {
                    try
                    {
                        ExecuteClientActionNewSM(
                            upgradeDeploymentInput,
                            CommandRuntime.ToString(),
                            () => this.ComputeClient.Deployments.UpgradeBySlot(
                                this.ServiceName,
                                (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true),
                                upgradeDeploymentInput));

                        if (removePackage == true)
                        {
                            this.RetryCall(s =>
                            AzureBlob.DeletePackageFromBlob(
                                    this.StorageClient,
                                    storageName,
                                    packageUrl));
                        }
                    }
                    catch (CloudException ex)
                    {
                        this.WriteExceptionDetails(ex);
                    }
                });
            }
            else if (string.Compare(this.ParameterSetName, "Config", StringComparison.OrdinalIgnoreCase) == 0)
            {
                // Config parameter set
                var changeDeploymentStatusParams = new DeploymentChangeConfigurationParameters
                {
                    Configuration = configString,
                    ExtensionConfiguration = extConfig
                };

                ExecuteClientActionNewSM(
                    changeDeploymentStatusParams,
                    CommandRuntime.ToString(),
                    () => this.ComputeClient.Deployments.ChangeConfigurationBySlot(
                        this.ServiceName,
                        (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true),
                        changeDeploymentStatusParams));
            }
            else
            {
                // Status parameter set
                var updateDeploymentStatusParams = new DeploymentUpdateStatusParameters
                {
                    Status = (UpdatedDeploymentStatus)Enum.Parse(typeof(UpdatedDeploymentStatus), this.NewStatus, true)
                };

                ExecuteClientActionNewSM(
                    null,
                    CommandRuntime.ToString(),
                    () => this.ComputeClient.Deployments.UpdateStatusByDeploymentSlot(
                    this.ServiceName,
                    (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true),
                    updateDeploymentStatusParams));
            }
        }