/// <summary>
 /// Constructs a GetHostedServiceList command
 /// </summary>
 // https://management.core.windows.net/<subscription-id>/services/hostedservices/<service-name>/deploymentslots/<deployment-slot>
 internal GetDeploymenRoleNamesCommand(string serviceName, DeploymentSlot slot = DeploymentSlot.Production)
 {
     OperationId = "hostedservices";
     ServiceType = "services";
     HttpCommand = (HostedServiceName = serviceName) + "/deploymentslots/" + slot.ToString().ToLower();
     HttpVerb    = HttpVerbGet;
 }
        /// <summary>
        /// Returns a list of Deployment objects for a given subscription
        /// </summary>
        /// <param name="serviceName">The name of the cloud service</param>
        /// <param name="slot">The slot being either Production or Staging</param>
        /// <returns></returns>
        protected DeploymentGetResponse GetAzureDeyployment(string serviceName, DeploymentSlot slot)
        {
            ComputeManagementClient client = new ComputeManagementClient(MyCloudCredentials);

            try
            {
                try
                {
                    return(client.Deployments.GetBySlot(serviceName, slot));
                }
                catch (CloudException ex)
                {
                    if (ex.ErrorCode == "ResourceNotFound")
                    {
                        Logger.Warn(ex, String.Format("Resource not found during retrieval of Deployment object for service: {0}, {1}", serviceName, ex.ErrorCode));
                        return(null);
                    }
                    else
                    {
                        Logger.Warn(ex, String.Format("Exception during retrieval of Deployment objects for the service: {0}, Errorcode: {1}", serviceName, ex.ErrorCode));
                        return(null);
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Warn(e, String.Format("Exception during retrieval of Deployment objects for the service: {0}", serviceName));
                return(null);
            }
        }
Example #3
0
        private void SetAzureReservedIPAssociationSimpleBySlot(DeploymentSlot slot)
        {
            SetAzureReservedIPAssociationCmdlet setassociation = new SetAzureReservedIPAssociationCmdlet(testClientProvider)
            {
                ReservedIPName = ReservedIPName,
                ServiceName    = ServiceName,
                Slot           = slot.ToString(),
                CommandRuntime = mockCommandRuntime,
            };

            // Action
            setassociation.ExecuteCmdlet();

            // Assert
            computeClientMock.Verify(
                c => c.Deployments.GetBySlotAsync(
                    ServiceName,
                    slot,
                    It.IsAny <CancellationToken>()),
                Times.Once);

            networkingClientMock.Verify(
                c => c.ReservedIPs.AssociateAsync(
                    ReservedIPName,
                    It.Is <NetworkReservedIPMobilityParameters>(
                        p =>
                        string.Equals(p.ServiceName, ServiceName) &&
                        string.IsNullOrEmpty(p.VirtualIPName) && string.Equals(p.DeploymentName, DeploymentName)),
                    It.IsAny <CancellationToken>()),
                Times.Once());
            Assert.Equal(1, mockCommandRuntime.OutputPipeline.Count);
            Assert.Equal("Succeeded", ((ManagementOperationContext)mockCommandRuntime.OutputPipeline[0]).OperationStatus);
        }
Example #4
0
 public FrontPageService(IFeaturedArticlesQuery articlesQuery, ITwitterQuery twitterQuery,
                         IOptions <DeploymentSlot> deploymentSlot)
 {
     this.articlesQuery  = articlesQuery;
     this.twitterQuery   = twitterQuery;
     this.deploymentSlot = deploymentSlot.Value;
 }
 /// <summary>
 /// Used to create an instance of GetAggregateDeploymentStatusCommand
 /// </summary>
 //https://management.core.windows.net/<subscription-id>/services/hostedservices/<service-name>/deploymentslots/<deployment-slot>
 internal GetAggregateDeploymentStatusCommand(string hostedServiceName, DeploymentSlot slot)
 {
     OperationId = "hostedservices";
     ServiceType = "services";
     HttpCommand = (HostedServiceName = hostedServiceName) + "/deploymentslots/" + slot.ToString().ToLower();
     HttpVerb    = HttpVerbGet;
 }
Example #6
0
 /// <summary>
 /// Constructs a command to create an update to the status of a role
 /// </summary>
 internal UpdateRoleStatusCommand(string serviceName, DeploymentSlot slot, UpdateDeploymentStatus status)
 {
     OperationId = "hostedservices";
     ServiceType = "services";
     HttpCommand = serviceName + "/deploymentslots/" + slot.ToString().ToLower() + "/?comp=status";
     Status      = status;
 }
        public XDocument GetConfiguration(SubscriptionCloudCredentials credentials, string serviceName, DeploymentSlot slot)
        {
            using (var client = CloudContext.Clients.CreateComputeManagementClient(credentials))
            {
                try
                {
                    var response = client.Deployments.GetBySlot(serviceName, slot);

                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        throw new Exception(string.Format("Getting deployment by slot returned HTTP Status Code: {0}",
                            response.StatusCode));
                    }

                    return string.IsNullOrEmpty(response.Configuration)
                        ? null
                        : XDocument.Parse(response.Configuration);
                }
                catch (CloudException cloudException)
                {
                    Log.VerboseFormat("Getting deployments for service '{0}', slot {1}, returned:\n{2}", serviceName, slot.ToString(), cloudException.Message);
                    return null;
                }
            }
        }
        protected PSArgument[] CreateDeploymentGetBySlotParameters()
        {
            string         serviceName    = string.Empty;
            DeploymentSlot deploymentSlot = new DeploymentSlot();

            return(ConvertFromObjectsToArguments(new string[] { "ServiceName", "DeploymentSlot" }, new object[] { serviceName, deploymentSlot }));
        }
 /// <summary>
 /// Constructs a command to create an update to the status of a role
 /// </summary>
 internal UpdateRoleStatusCommand(string serviceName, DeploymentSlot slot, UpdateDeploymentStatus status)
 {
     OperationId = "hostedservices";
     ServiceType = "services";
     HttpCommand = serviceName + "/deploymentslots/" + slot.ToString().ToLower() + "/?comp=status";
     Status = status;
 }
 /// <summary>
 /// Constructs a GetHostedServiceList command
 /// </summary>
 internal GetHostedServiceContainsDeploymentCommand(string serviceName, DeploymentSlot slot = DeploymentSlot.Production)
 {
     OperationId = "hostedservices";
     ServiceType = "services";
     HttpCommand = (HostedServiceName = serviceName) + "/deploymentslots/" + slot.ToString().ToLower();
     HttpVerb = HttpVerbGet;
 }
Example #11
0
        /// <summary>
        /// Check if the deployment exists for given cloud service.
        /// </summary>
        /// <param name="name">The cloud service name</param>
        /// <param name="slot">The deployment slot name</param>
        /// <returns>Flag indicating the deployment exists or not</returns>
        public bool DeploymentExists(string name = null, string slot = null)
        {
            DeploymentSlot deploymentSlot = GetSlot(slot);
            string         deploymentName = null;

            return(DeploymentExists(name, deploymentSlot, out deploymentName));
        }
 /// <summary>
 /// Used to create an instance of GetAggregateDeploymentStatusCommand
 /// </summary>
 //https://management.core.windows.net/<subscription-id>/services/hostedservices/<service-name>/deploymentslots/<deployment-slot>
 internal GetAggregateDeploymentStatusCommand(string hostedServiceName, DeploymentSlot slot)
 {
     OperationId = "hostedservices";
     ServiceType = "services";
     HttpCommand = (HostedServiceName = hostedServiceName) + "/deploymentslots/" + slot.ToString().ToLower();
     HttpVerb = HttpVerbGet;
 }
 /// <summary>
 /// Used to construct the ServiceClient
 /// </summary>
 public ServiceClient(string subscriptionId, X509Certificate2 certificate, string cloudService, DeploymentSlot slot = DeploymentSlot.Production)
 {
     SubscriptionId        = subscriptionId;
     ManagementCertificate = certificate;
     Name = cloudService;
     Slot = slot;
 }
 /// <summary>
 /// Returns a list of Deployment objects for a given subscription
 /// </summary>
 /// <param name="serviceName">The name of the cloud service</param>
 /// <param name="slot">The slot being either Production or Staging</param>
 /// <returns></returns>
 protected DeploymentGetResponse GetAzureDeyployment(string serviceName, DeploymentSlot slot)
 {
     ComputeManagementClient client = new ComputeManagementClient(MyCloudCredentials);
     try
     {
         try
         {
             return client.Deployments.GetBySlot(serviceName, slot);
         }
         catch (CloudException ex)
         {
             if (ex.ErrorCode == "ResourceNotFound")
             {
                 Logger.Warn(ex, String.Format("Resource not found during retrieval of Deployment object for service: {0}, {1}", serviceName, ex.ErrorCode));
                 return null;
             }
             else
             {
                 Logger.Warn(ex, String.Format("Exception during retrieval of Deployment objects for the service: {0}, Errorcode: {1}", serviceName, ex.ErrorCode));
                 return null;
             }
         }
     }
     catch (Exception e)
     {
         Logger.Warn(e, String.Format("Exception during retrieval of Deployment objects for the service: {0}", serviceName));
         return null;
     }
 }
Example #15
0
        /// <summary>
        ///     Create or update hosted service deployment
        /// </summary>
        /// <param name="hostedServiceName"></param>
        /// <param name="packageLocation"></param>
        /// <param name="configPath"></param>
        /// <param name="deploymentName"></param>
        /// <param name="deploymentSlot"></param>
        /// <returns></returns>
        public DeploymentGetResponse CreateOrUpdateDeployment(string hostedServiceName, Uri packageLocation, string configPath, string deploymentName = "",
                                                              DeploymentSlot deploymentSlot = DeploymentSlot.Production)
        {
            if (!File.Exists(configPath))
            {
                throw new FileNotFoundException(string.Format("The file '{0}' cannot be found or the caller does not have sufficient permissions to read it.", configPath));
            }

            if (string.IsNullOrEmpty(deploymentName))
            {
                deploymentName = Dependencies.TestResourcesCollector.GetUniqueDeploymentName();
            }

            return(CreateOrUpdateDeployment(hostedServiceName,
                                            new DeploymentCreateParameters
            {
                Name = deploymentName,
                Configuration = GetSettingsFromPackageConfig(configPath),
                PackageUri = packageLocation,
                Label = AzureServiceConstants.DefaultLabel,
                StartDeployment = true,
                TreatWarningsAsError = false
            },
                                            deploymentSlot));
        }
 /// <summary>
 /// Used to create a role context
 /// </summary>
 internal RoleContextManager(string subscriptionId, X509Certificate2 certificate, string serviceName, DeploymentSlot slot)
 {
     SubscriptionId        = subscriptionId;
     ManagementCertificate = certificate;
     ServiceName           = serviceName;
     DeploymentSlot        = slot;
 }
 /// <summary>
 /// Used to create a role context
 /// </summary>
 internal RoleContextManager(string subscriptionId, X509Certificate2 certificate, string serviceName, DeploymentSlot slot)
 {
     SubscriptionId = subscriptionId;
     ManagementCertificate = certificate;
     ServiceName = serviceName;
     DeploymentSlot = slot;
 }
 /// <summary>
 /// Used to construct the ServiceClient
 /// </summary>
 public ServiceClient(string subscriptionId, X509Certificate2 certificate, string cloudService, DeploymentSlot slot = DeploymentSlot.Production)
 {
     SubscriptionId = subscriptionId;
     ManagementCertificate = certificate;
     Name = cloudService;
     Slot = slot;
 }
 public virtual async Task<OperationResponse> ChangeDeploymentConfiguration(XDocument serviceConfiguration, DeploymentSlot slot = DeploymentSlot.Production)
 {
     return await ChangeDeploymentConfiguration(new DeploymentChangeConfigurationParameters
     {
         Configuration = serviceConfiguration.ToString(),
         Mode = DeploymentChangeConfigurationMode.Auto,
     }, slot);
 }
Example #20
0
 /// <summary>
 /// Used to construct a RoleStatusWatcher
 /// </summary>
 /// <param name="serviceName">The name of the hosted service</param>
 /// <param name="roleName">the name of the role</param>
 /// <param name="slot">Production or Staging</param>
 /// <param name="managementCertificate">the management certificate used with this role</param>
 /// <param name="subscriptionId">The id of the subscription we're interested in</param>
 internal RoleStatusWatcher(string serviceName, string roleName, DeploymentSlot slot,
                            X509Certificate2 managementCertificate, string subscriptionId)
     : base(serviceName, managementCertificate, subscriptionId)
 {
     RoleName            = roleName;
     ProductionOrStaging = slot;
     CurrentState        = RoleStatus.Unknown;
 }
Example #21
0
 /// <summary>
 ///     Reboot worker role
 /// </summary>
 /// <param name="hostedServiceName"></param>
 /// <param name="slot"></param>
 /// <param name="roleInstanceName"></param>
 public void RebootDeploymentRoleInstanceBySlot(string hostedServiceName, DeploymentSlot slot, string roleInstanceName)
 {
     ComputeManagementClient.Deployments.RebootRoleInstanceByDeploymentSlotAsync(
         hostedServiceName,
         slot,
         roleInstanceName,
         new CancellationToken());
 }
Example #22
0
        protected PSArgument[] CreateDeploymentChangeConfigurationBySlotParameters()
        {
            string         serviceName    = string.Empty;
            DeploymentSlot deploymentSlot = new DeploymentSlot();
            DeploymentChangeConfigurationParameters parameters = new DeploymentChangeConfigurationParameters();

            return(ConvertFromObjectsToArguments(new string[] { "ServiceName", "DeploymentSlot", "Parameters" }, new object[] { serviceName, deploymentSlot, parameters }));
        }
Example #23
0
 private void DeleteDeploymentIfExists(string name, DeploymentSlot slot)
 {
     if (DeploymentExists(name, slot))
     {
         WriteVerboseWithTimestamp(Resources.RemoveDeploymentWaitMessage, slot, name);
         TranslateException(() => ComputeClient.Deployments.DeleteBySlot(name, slot));
     }
 }
Example #24
0
        protected PSArgument[] CreateDeploymentWalkUpgradeDomainByDeploymentSlotParameters()
        {
            string         serviceName    = string.Empty;
            DeploymentSlot deploymentSlot = new DeploymentSlot();
            DeploymentWalkUpgradeDomainParameters parameters = new DeploymentWalkUpgradeDomainParameters();

            return(ConvertFromObjectsToArguments(new string[] { "ServiceName", "DeploymentSlot", "Parameters" }, new object[] { serviceName, deploymentSlot, parameters }));
        }
Example #25
0
        protected PSArgument[] CreateDeploymentReimageRoleInstanceByDeploymentSlotParameters()
        {
            string         serviceName      = string.Empty;
            DeploymentSlot deploymentSlot   = new DeploymentSlot();
            string         roleInstanceName = string.Empty;

            return(ConvertFromObjectsToArguments(new string[] { "ServiceName", "DeploymentSlot", "RoleInstanceName" }, new object[] { serviceName, deploymentSlot, roleInstanceName }));
        }
Example #26
0
 // https://management.core.windows.net/<subscription-id>/services/hostedservices/<service-name>/deploymentslots/<deployment-slot>
 /// <summary>
 /// Constructs a service deployment delete command with a given name and slot
 /// </summary>
 /// <param name="serviceName">The name of the service which is being swept for deployments</param>
 /// <param name="slot">The deployment slot used can be production or staging</param>
 internal DeleteDeploymentCommand(string serviceName, DeploymentSlot slot)
 {
     Name           = serviceName;
     DeploymentSlot = slot;
     HttpVerb       = HttpVerbDelete;
     HttpCommand    = Name + "/deploymentslots/" + slot.ToString().ToLower();
     ServiceType    = "services";
     OperationId    = "hostedservices";
 }
Example #27
0
 /// <summary>
 ///     Update hosted service deployment by slot
 /// </summary>
 /// <param name="hostedServiceName"></param>
 /// <param name="slot"></param>
 /// <param name="status"></param>
 public void UpdateDeploymentStatusBySlot(string hostedServiceName, DeploymentSlot slot, UpdatedDeploymentStatus status)
 {
     ComputeManagementClient.Deployments.UpdateStatusByDeploymentSlotAsync(hostedServiceName,
                                                                           slot,
                                                                           new DeploymentUpdateStatusParameters {
         Status = status
     },
                                                                           new CancellationToken()).Wait();
 }
Example #28
0
 /// <summary>
 /// Constructs a GetHostedServiceList command
 /// </summary>
 // https://management.core.windows.net/<subscription-id>/services/hostedservices/<service-name>/deploymentslots/<deployment-slot>
 internal GetDeploymenConfigurationCommand(string serviceName, DeploymentSlot slot = DeploymentSlot.Production)
 {
     // need to increment the version in this request otherwise will not be able to check vm instances
     AdditionalHeaders["x-ms-version"] = "2012-03-01";
     OperationId = "hostedservices";
     ServiceType = "services";
     HttpCommand = (HostedServiceName = serviceName) + "/deploymentslots/" + slot.ToString().ToLower();
     HttpVerb    = HttpVerbGet;
 }
        protected void ExecuteDeploymentGetBySlotMethod(object[] invokeMethodInputParameters)
        {
            string         serviceName    = (string)ParseParameter(invokeMethodInputParameters[0]);
            DeploymentSlot deploymentSlot = (DeploymentSlot)ParseParameter(invokeMethodInputParameters[1]);

            var result = DeploymentClient.GetBySlot(serviceName, deploymentSlot);

            WriteObject(result);
        }
 /// <summary>
 /// Constructs a GetHostedServiceList command
 /// </summary>
 // https://management.core.windows.net/<subscription-id>/services/hostedservices/<service-name>/deploymentslots/<deployment-slot>
 internal GetDeploymenConfigurationCommand(string serviceName, DeploymentSlot slot = DeploymentSlot.Production)
 {
     // need to increment the version in this request otherwise will not be able to check vm instances
     AdditionalHeaders["x-ms-version"] = "2012-03-01";
     OperationId = "hostedservices";
     ServiceType = "services";
     HttpCommand = (HostedServiceName = serviceName) + "/deploymentslots/" + slot.ToString().ToLower();
     HttpVerb = HttpVerbGet;
 }
 // https://management.core.windows.net/<subscription-id>/services/hostedservices/<service-name>/deploymentslots/<deployment-slot>
 /// <summary>
 /// Constructs a service deployment delete command with a given name and slot 
 /// </summary>
 /// <param name="serviceName">The name of the service which is being swept for deployments</param>
 /// <param name="slot">The deployment slot used can be production or staging</param>
 internal DeleteDeploymentCommand(string serviceName, DeploymentSlot slot)
 {
     Name = serviceName;
     DeploymentSlot = slot;
     HttpVerb = HttpVerbDelete;
     HttpCommand = Name + "/deploymentslots/" + slot.ToString().ToLower();
     ServiceType = "services";
     OperationId = "hostedservices";
 }
        protected PSArgument[] CreateDeploymentListEventsBySlotParameters()
        {
            string         serviceName    = string.Empty;
            DeploymentSlot deploymentSlot = new DeploymentSlot();
            DateTime       startTime      = new DateTime();
            DateTime       endTime        = new DateTime();

            return(ConvertFromObjectsToArguments(new string[] { "ServiceName", "DeploymentSlot", "StartTime", "EndTime" }, new object[] { serviceName, deploymentSlot, startTime, endTime }));
        }
 /// <summary>
 /// Used to create an instance of GetRoleStatusCommand
 /// </summary>
 //https://management.core.windows.net/<subscription-id>/services/hostedservices/<service-name>/deploymentslots/<deployment-slot>
 internal GetRoleStatusCommand(string hostedServiceName, string roleName, DeploymentSlot slot)
 {
     OperationId = "hostedservices";
     ServiceType = "services";
     HttpCommand = (HostedServiceName = hostedServiceName) + "/deploymentslots/" + slot.ToString().ToLower();
     ;
     HttpVerb = HttpVerbGet;
     RoleName = roleName;
     Slot = slot;
 }
Example #34
0
        protected void ExecuteDeploymentWalkUpgradeDomainByDeploymentSlotMethod(object[] invokeMethodInputParameters)
        {
            string         serviceName    = (string)ParseParameter(invokeMethodInputParameters[0]);
            DeploymentSlot deploymentSlot = (DeploymentSlot)ParseParameter(invokeMethodInputParameters[1]);
            DeploymentWalkUpgradeDomainParameters parameters = (DeploymentWalkUpgradeDomainParameters)ParseParameter(invokeMethodInputParameters[2]);

            var result = DeploymentClient.WalkUpgradeDomainByDeploymentSlot(serviceName, deploymentSlot, parameters);

            WriteObject(result);
        }
 /// <summary>
 /// Constructs a SetDeploymenConfigurationCommand command
 /// </summary>
 // POST https://management.core.windows.net/<subscription-id>/services/hostedservices/<service-name>/deploymentslots/<deployment-slot>/?comp=config
 internal SetDeploymenConfigurationCommand(string serviceName, CscfgFile config, DeploymentSlot slot = DeploymentSlot.Production)
 {
     // need to increment the version in this request otherwise will not be able to check vm instances
     AdditionalHeaders["x-ms-version"] = "2012-03-01";
     OperationId = "hostedservices";
     ServiceType = "services";
     HttpCommand = (CloudServiceName = serviceName) + "/deploymentslots/" + (Slot = slot).ToString().ToLower() + "/?comp=config";
     Configuration = config;
     HttpVerb = HttpVerbPost;
 }
Example #36
0
        protected void ExecuteDeploymentReimageRoleInstanceByDeploymentSlotMethod(object[] invokeMethodInputParameters)
        {
            string         serviceName      = (string)ParseParameter(invokeMethodInputParameters[0]);
            DeploymentSlot deploymentSlot   = (DeploymentSlot)ParseParameter(invokeMethodInputParameters[1]);
            string         roleInstanceName = (string)ParseParameter(invokeMethodInputParameters[2]);

            var result = DeploymentClient.ReimageRoleInstanceByDeploymentSlot(serviceName, deploymentSlot, roleInstanceName);

            WriteObject(result);
        }
        /// <summary>
        /// Used to delete a deployment in a respective slot
        /// </summary>
        /// <param name="slot">Either production or staging</param>
        public void DeleteDeployment(DeploymentSlot slot = DeploymentSlot.Production)
        {
            var deleteDeployment = new DeleteDeploymentCommand(Name, slot)
            {
                Certificate    = ManagementCertificate,
                SubscriptionId = SubscriptionId
            };

            deleteDeployment.Execute();
        }
Example #38
0
        public Deployment(string deploymentName, DeploymentSlot deploymentSlot, ServiceConfiguration serviceConfig)
            : this()
        {
            Contract.Requires(deploymentName != null);
            Contract.Requires(serviceConfig != null);

            Name = Label = deploymentName;
            Slot = deploymentSlot;
            Configuration = serviceConfig;
        }
Example #39
0
        protected void ExecuteDeploymentChangeConfigurationBySlotMethod(object[] invokeMethodInputParameters)
        {
            string         serviceName    = (string)ParseParameter(invokeMethodInputParameters[0]);
            DeploymentSlot deploymentSlot = (DeploymentSlot)ParseParameter(invokeMethodInputParameters[1]);
            DeploymentChangeConfigurationParameters parameters = (DeploymentChangeConfigurationParameters)ParseParameter(invokeMethodInputParameters[2]);

            var result = DeploymentClient.ChangeConfigurationBySlot(serviceName, deploymentSlot, parameters);

            WriteObject(result);
        }
Example #40
0
        public Deployment(string deploymentName, DeploymentSlot deploymentSlot, ServiceConfiguration serviceConfig)
            : this()
        {
            Contract.Requires(deploymentName != null);
            Contract.Requires(serviceConfig != null);

            Name          = Label = deploymentName;
            Slot          = deploymentSlot;
            Configuration = serviceConfig;
        }
 /// <summary>
 /// Used to create an instance of GetRoleStatusCommand
 /// </summary>
 //https://management.core.windows.net/<subscription-id>/services/hostedservices/<service-name>/deploymentslots/<deployment-slot>
 internal GetRoleStatusCommand(string hostedServiceName, string roleName, DeploymentSlot slot)
 {
     OperationId = "hostedservices";
     ServiceType = "services";
     HttpCommand = (HostedServiceName = hostedServiceName) + "/deploymentslots/" + slot.ToString().ToLower();
     ;
     HttpVerb = HttpVerbGet;
     RoleName = roleName;
     Slot     = slot;
 }
Example #42
0
        private static void WaitForDeploymentStatus(
            DeploymentStatus deploymentStatus,
            InstanceStatus instanceStatus,
            string subscriptionId,
            string serviceName,
            DeploymentSlot deploymentSlot,
            X509Certificate2 managementCertificate,
            bool mostIsGoodEnough)
        {
            // assume we haven't matched the desired status
            bool statusMatches = false;

            do
            {
                // sleep for a bit...
                Thread.Sleep(TimeSpan.FromSeconds(5));
                WriteStatus(".");

                // get the current status
                FullDeploymentStatus current = Utilities.GetDeploymentSlotStatus(
                    subscriptionId,
                    serviceName,
                    deploymentSlot,
                    managementCertificate);

                // if the main status matches
                if (current.MainStatus == deploymentStatus)
                {
                    // good so far...
                    statusMatches = true;
                    int countMatch = 0;

                    // see if all instance status's also match
                    foreach (InstanceDetails instance in current.Instances)
                    {
                        if (instance.Status != instanceStatus)
                        {
                            // we have a bad apple
                            statusMatches = false;
                        }
                        else
                        {
                            countMatch++;
                        }
                    }

                    if (mostIsGoodEnough && ((double)countMatch / current.Instances.Count) >= 0.8)
                    {
                        statusMatches = true;
                    }
                }
            }while (!statusMatches);

            WriteStatusLine(string.Format(" {0}", deploymentStatus));
        }
        /// <summary>
        /// Begins an asychronous operation to change the configuration of a deployment.
        /// </summary>
        /// <param name="cloudServiceName">The name of the cloud service which contains the deployment with the configuration to be changed. Required.</param>
        /// <param name="slot">The <see cref="DeploymentSlot"/> which contains the deployment with the configuration to be changed.</param>
        /// <param name="configFilePath">The local file path to the Azure deployment configuration file (.cscfg) defining the deployment. Required.</param>
        /// <param name="treatWarningsAsError">Set to true to treat configuation warnings as errors and fail the configuration change. Default is false.</param>
        /// <param name="mode">The <see cref="UpgradeType"/> value indicating whether the configuation change should happen automatically (<see cref="UpgradeType.Auto"/> or
        /// manually (<see cref="UpgradeType.Manual"/>. If set to <see cref="UpgradeType.Manual"/>, you must subsequently call <see cref="WalkUpgradeDomainAsync"/> to
        /// control the configuration change across the deployment.</param>
        /// <param name="extendedProperties">An optional <see cref="IDictionary{String, String}"/> that contains Name Value pairs representing user defined metadata for the deployment.</param>
        /// <param name="token">An optional <see cref="CancellationToken"/>.</param>
        /// <returns>A <see cref="Task"/> which returns a string representing the operation Id for this operation.</returns>
        /// <remarks>ChangeDeploymentConfigurationAsync is a long-running asynchronous operation. When the Task representing ChangeDeploymentConfigurationAsync is complete,
        /// without throwing an exception, this indicates that the operation as been accepted by the server, but has not completed. To track progress of
        /// the long-running operation use the operation Id returned from the ChangeDeploymentConfigurationAsync <see cref="Task"/> in calls to <see cref="GetOperationStatusAsync"/>
        /// until it returns either <see cref="OperationStatus.Succeeded"/> or <see cref="OperationStatus.Failed"/>.</remarks>
        public Task<string> ChangeDeploymentConfigurationAsync(string cloudServiceName, DeploymentSlot slot, string configFilePath, bool treatWarningsAsError = false, UpgradeType mode = UpgradeType.Auto, IDictionary<string, string> extendedProperties = null, CancellationToken token = default(CancellationToken))
        {
            Validation.ValidateStringArg(cloudServiceName, "cloudServiceName");

            //this validates the other parameters...
            ChangeDeploymentConfigurationInfo info = ChangeDeploymentConfigurationInfo.Create(configFilePath, treatWarningsAsError, mode, extendedProperties);

            HttpRequestMessage message = CreateBaseMessage(HttpMethod.Post, CreateTargetUri(UriFormatStrings.DeploymentSlotChangeConfig, cloudServiceName, slot.ToString()), info);

            return StartSendTask(message, token);
        }
Example #44
0
        private void CreateDeployment(string serviceName, DeploymentSlot slot,
                                      DeploymentCreateParameters createParameters)
        {
            var service = Services.First(s => s.Name == serviceName);

            service.AddDeployment(d =>
            {
                d.Name = createParameters.Name;
                d.Slot = slot;
            });
        }
        public Task<int> GetRoleInstanceCount(string serviceName, string roleName, DeploymentSlot deploymentSlot, CancellationToken cancellationToken)
        {
            var client = HttpClientFactory.Create(_subscriptionId, _certificate);
            var completionSource = new TaskCompletionSource<int>();

            DoGetDeploymentConfiguration(client, serviceName, deploymentSlot, cancellationToken).ContinuePropagateWith(
                completionSource, cancellationToken,
                queryTask => completionSource.TrySetResult(Int32.Parse(GetInstanceCountConfigElement(queryTask.Result, roleName).Value)));

            completionSource.Task.ContinueRaiseSystemEventOnFault(_observer, EventForFailedOperation);

            return completionSource.Task;
        }
 /// <summary>
 /// Constructs a command to create a deployment to a particular cloud service
 /// </summary>
 /// <param name="serviceName">the name of the cloud service</param>
 /// <param name="deploymentName">The name of the deployment</param>
 /// <param name="packageUri">The blob store and endpoint address where the package has been uploaded to</param>
 /// <param name="config">The base64 encoded config of .cscfg file</param>
 /// <param name="slot">The deployment slot - can be production or staging</param>
 /// <param name="startDeployment">an optional parameter which defaults to true as to whether the deployment should be started when complete</param>
 /// <param name="treatWarningsAsErrors">an optional parameter set to false - any warnings (such as SLA or config violations) will be treated as an error and stop the deployment</param>
 internal CreateDeploymentCommand(string serviceName, string deploymentName, string packageUri, string config,
                                  DeploymentSlot slot, bool startDeployment = true,
                                  bool treatWarningsAsErrors = false)
 {
     OperationId = "hostedservices";
     ServiceType = "services";
     Name = serviceName;
     DeploymentSlot = slot;
     DeploymentName = deploymentName;
     PackageUri = packageUri;
     Config = config;
     HttpCommand = Name + "/deploymentslots/" + slot.ToString().ToLower();
     StartDeploymentAutomatically = startDeployment;
     TreatWarningsAsErrors = treatWarningsAsErrors;
 }
        private void VerifyDeploymentExists(HostedServiceGetDetailedResponse cloudService, DeploymentSlot slot)
        {
            bool exists = false;

            if (cloudService.Deployments != null)
            {
                exists = cloudService.Deployments.Any(d => d.DeploymentSlot == slot );
            }

            if (!exists)
            {
                throw new Exception(string.Format(Resources.CannotFindDeployment, cloudService.ServiceName, slot));
            }
            
        }
        /// <summary>
        /// Gets the AzureDeployment for a specifc slot on a cloud service.
        /// </summary>
        /// <param name="client">The <see cref="ComputeManagementClient"/> that is performing the operation.</param>
        /// <param name="serviceName">The name of the cloud service.</param>
        /// <param name="slot">The name of the Cloud Service slot.</param>
        /// <returns>The cloud service deployment.</returns>
        public static async Task<DeploymentGetResponse> GetAzureDeyploymentAsync(this ComputeManagementClient client, string serviceName, DeploymentSlot slot)
        {
            Contract.Requires(client != null);

            try
            {
                return await client.Deployments.GetBySlotAsync(serviceName, slot);
            }
            catch (CloudException cex)
            {
                if (cex.Error.Code == "ResourceNotFound")
                {
                    return null;
                }

                throw;
            }
        }
 /// <summary>
 ///     Create or update hosted service deployment
 /// </summary>
 /// <param name="hostedServiceName"></param>
 /// <param name="input"></param>
 /// <param name="deploymentSlot"></param>
 /// <returns></returns>
 public DeploymentGetResponse CreateOrUpdateDeployment(string hostedServiceName,
                                        DeploymentCreateParameters input,
                                        DeploymentSlot deploymentSlot = DeploymentSlot.Production)
 {
     return GetDeployment(hostedServiceName, input.Name) ?? CreateDeployment(hostedServiceName, input, deploymentSlot);
 }
        /// <summary>
        ///     Returns hosing service deployment by slot
        /// </summary>
        /// <param name="hostedServiceName"></param>
        /// <param name="slot"></param>
        /// <returns></returns>
        public DeploymentGetResponse GetDeploymentBySlot(string hostedServiceName, DeploymentSlot slot)
        {
            try
            {
                var result = ComputeManagementClient.Deployments.GetBySlotAsync(hostedServiceName, slot, new CancellationToken()).Result;

                return result;
            }
            catch
            {
            }

            return null;
        }
        /// <summary>
        ///     Create hosted service deployment
        /// </summary>
        /// <param name="hostedServiceName"></param>
        /// <param name="input"></param>
        /// <param name="deploymentSlot"></param>
        /// <returns></returns>
        public DeploymentGetResponse CreateDeployment(string hostedServiceName, DeploymentCreateParameters input,
            DeploymentSlot deploymentSlot = DeploymentSlot.Production)
        {
            TestEasyLog.Instance.Info(string.Format("Creating Deployment... Name: '{0}', Label: '{1}'", input.Name, input.Label));

            ComputeManagementClient.Deployments.CreateAsync(hostedServiceName,
                deploymentSlot,
                input,
                new CancellationToken()).Wait();

            var result = GetDeployment(hostedServiceName, input.Name);

            Dependencies.TestResourcesCollector.Remember(
                AzureResourceType.Deployment,
                result.Name,
                new DeploymentInfo { Deployment = result, HostedService = hostedServiceName });

            return result;
        }
        /// <summary>
        /// Begins an asychronous operation to upgrade a deployment.
        /// </summary>
        /// <param name="cloudServiceName">The name of the cloud service which contains the deployment to be upgraded. Required.</param>
        /// <param name="slot">The <see cref="DeploymentSlot"/> which contains the deployment to be upgraded.</param>
        /// <param name="mode">The <see cref="UpgradeType"/> value indicating whether the ugrade should happen automatically (<see cref="UpgradeType.Auto"/> or
        /// manually (<see cref="UpgradeType.Manual"/>. If set to <see cref="UpgradeType.Manual"/>, you must subsequently call <see cref="WalkUpgradeDomainAsync"/> to
        /// control the upgrade across the deployment.</param>
        /// <param name="packageUrl">The <see cref="Uri"/> representing the location of the azure deployment package (.cspkg) to be deployed.
        /// The service package can be located either in a storage account beneath the same subscription or a Shared Access Signature (SAS) URI from any storage account. 
        /// For more info about Shared Access Signatures, see <see href="http://msdn.microsoft.com/en-us/library/windowsazure/ee395415">Using a Shared Access Signature (REST API)</see>. Required.
        /// </param>
        /// <param name="configFilePath">The local file path to the Azure deployment configuration file (.cscfg) defining the deployment. Required.</param>
        /// <param name="label">The label for the deployment, may be up to 100 characters in length. Required.</param>
        /// <param name="roleToUpgrade">The name of a specific role to upgrade. Optional.</param>
        /// <param name="treatWarningsAsError">Specifies whether to treat package validation warnings as errors and fail the upgrade. Default is false.</param>
        /// <param name="force">Specifies whether the upgrade should proceed even when it will cause local data to be lost from some role instances. Default is false.</param>
        /// <param name="extendedProperties">An optional <see cref="IDictionary{String, String}"/> that contains Name Value pairs representing user defined metadata for the service.</param>
        /// <param name="token">An optional <see cref="CancellationToken"/>.</param>
        /// <returns>A <see cref="Task"/> which returns a string representing the operation Id for this operation.</returns>
        /// <remarks>UpgradeDeploymentAsync is a long-running asynchronous operation. When the Task representing UpgradeDeploymentAsync is complete,
        /// without throwing an exception, this indicates that the operation as been accepted by the server, but has not completed. To track progress of
        /// the long-running operation use the operation Id returned from the UpgradeDeploymentAsync <see cref="Task"/> in calls to <see cref="GetOperationStatusAsync"/>
        /// until it returns either <see cref="OperationStatus.Succeeded"/> or <see cref="OperationStatus.Failed"/>.</remarks>
        public Task<string> UpgradeDeploymentAsync(string cloudServiceName, DeploymentSlot slot, UpgradeType mode, Uri packageUrl, string configFilePath, string label, string roleToUpgrade = null, bool treatWarningsAsError = false, bool force = false, IDictionary<string, string> extendedProperties = null, CancellationToken token = default(CancellationToken))
        {
            Validation.ValidateStringArg(cloudServiceName, "cloudServiceName");

            //this validates the other parameters...
            UpgradeDeploymentInfo info = UpgradeDeploymentInfo.Create(mode, packageUrl, configFilePath, label, roleToUpgrade, treatWarningsAsError, force, extendedProperties);

            HttpRequestMessage message = CreateBaseMessage(HttpMethod.Post, CreateTargetUri(UriFormatStrings.DeploymentSlotUpgrade, cloudServiceName, slot.ToString()), info);

            return StartSendTask(message, token);
        }
        /// <summary>
        /// Begins an asychronous operation to upgrade a particular domain in a manual deployment upgrade or configuration change.
        /// </summary>
        /// <param name="cloudServiceName">The name of the cloud service which contains the deployment to upgrade.</param>
        /// <param name="slot">The <see cref="DeploymentSlot"/> which contains the deployment to upgrade.</param>
        /// <param name="upgradeDomain">In integer representing the particular upgrade domain to upgrade.</param>
        /// <param name="token">An optional <see cref="CancellationToken"/>.</param>
        /// <returns>A <see cref="Task"/> which returns a string representing the operation Id for this operation.</returns>
        /// <remarks>WalkUpgradeDomainAsync is a long-running asynchronous operation. When the Task representing WalkUpgradeDomainAsync is complete,
        /// without throwing an exception, this indicates that the operation as been accepted by the server, but has not completed. To track progress of
        /// the long-running operation use the operation Id returned from the WalkUpgradeDomainAsync <see cref="Task"/> in calls to <see cref="GetOperationStatusAsync"/>
        /// until it returns either <see cref="OperationStatus.Succeeded"/> or <see cref="OperationStatus.Failed"/>.</remarks>
        public Task<string> WalkUpgradeDomainAsync(string cloudServiceName, DeploymentSlot slot, int upgradeDomain, CancellationToken token = default(CancellationToken))
        {
            Validation.ValidateStringArg(cloudServiceName, "cloudServiceName");

            WalkUpgradeDomainInfo info = WalkUpgradeDomainInfo.Create(upgradeDomain);

            HttpRequestMessage message = CreateBaseMessage(HttpMethod.Post, CreateTargetUri(UriFormatStrings.DeploymentSlotWalkUpgradeDomain, cloudServiceName, slot.ToString()), info);

            return StartSendTask(message, token);
        }
        /// <summary>
        /// Begins an asychronous operation to get properties for a deployment.
        /// </summary>
        /// <param name="cloudServiceName">The name of the cloud service which contains the deployment. Required.</param>
        /// <param name="slot">The <see cref="DeploymentSlot"/> which contains the deployment.</param>
        /// <param name="token">An optional <see cref="CancellationToken"/>.</param>
        /// <returns>A <see cref="Task"/> which returns a <see cref="Deployment"/>.</returns>
        public Task<Deployment> GetDeploymentAsync(string cloudServiceName, DeploymentSlot slot, CancellationToken token = default(CancellationToken))
        {
            Validation.ValidateStringArg(cloudServiceName, "cloudServiceName");

            HttpRequestMessage message = CreateBaseMessage(HttpMethod.Get, CreateTargetUri(UriFormatStrings.DeploymentSlot, cloudServiceName, slot.ToString()));

            return StartGetTask<Deployment>(message, token);
        }
        /// <summary>
        /// Begins an asychronous operation to stop a running deployment.
        /// </summary>
        /// <param name="cloudServiceName">The name of the cloud service which contains the deployment to be stopped. Required.</param>
        /// <param name="slot">The <see cref="DeploymentSlot"/> which contains the deployment to be stopped.</param>
        /// <param name="token">An optional <see cref="CancellationToken"/>.</param>
        /// <returns>A <see cref="Task"/> which returns a string representing the operation Id for this operation.</returns>
        /// <remarks>StopDeploymentAsync is a long-running asynchronous operation. When the Task representing StopDeploymentAsync is complete,
        /// without throwing an exception, this indicates that the operation as been accepted by the server, but has not completed. To track progress of
        /// the long-running operation use the operation Id returned from the StopDeploymentAsync <see cref="Task"/> in calls to <see cref="GetOperationStatusAsync"/>
        /// until it returns either <see cref="OperationStatus.Succeeded"/> or <see cref="OperationStatus.Failed"/>.</remarks>
        public Task<string> StopDeploymentAsync(string cloudServiceName, DeploymentSlot slot, CancellationToken token = default(CancellationToken))
        {
            Validation.ValidateStringArg(cloudServiceName, "cloudServiceName");

            UpdateDeploymentStatusInfo info = UpdateDeploymentStatusInfo.Create(false);

            HttpRequestMessage message = CreateBaseMessage(HttpMethod.Post, CreateTargetUri(UriFormatStrings.DeploymentSlotUpdateStatus, cloudServiceName, slot.ToString()), info);

            return StartSendTask(message, token);
        }
 /// <summary>
 ///     Update hosted service deployment by slot
 /// </summary>
 /// <param name="hostedServiceName"></param>
 /// <param name="slot"></param>
 /// <param name="status"></param>
 public void UpdateDeploymentStatusBySlot(string hostedServiceName, DeploymentSlot slot, UpdatedDeploymentStatus status)
 {
     ComputeManagementClient.Deployments.UpdateStatusByDeploymentSlotAsync(hostedServiceName,
         slot,
         new DeploymentUpdateStatusParameters { Status = status },
         new CancellationToken()).Wait();
 }
 /// <summary>
 ///     Delete hosted service deployment by slot
 /// </summary>
 /// <param name="hostedServiceName"></param>
 /// <param name="slot"></param>
 public void DeleteDeploymentBySlot(string hostedServiceName, DeploymentSlot slot)
 {
     ComputeManagementClient.Deployments.DeleteBySlotAsync(hostedServiceName, slot, new CancellationToken()).Wait();
 }
        /// <summary>
        ///     Deploy worker role
        /// </summary>
        /// <param name="packagePath"></param>
        /// <param name="configPath"></param>
        /// <param name="roleName"></param>
        /// <param name="deploymentSlot"></param>
        /// <returns></returns>
        public DeploymentInfo DeployRole(string packagePath, string configPath, string roleName = "",
            DeploymentSlot deploymentSlot = DeploymentSlot.Production)
        {
            var storageManager = new AzureStorageServiceManager();

            var service = storageManager.CreateStorageService();
            var blob = service.CreateBlob(Path.GetFileName(packagePath));
            var packageBlobUri = blob.UploadFile(packagePath);

            roleName = CreateHostedService(roleName);

            var deployment = CreateOrUpdateDeployment(roleName, packageBlobUri, configPath, deploymentSlot: deploymentSlot);

            return new DeploymentInfo { HostedService = roleName, Deployment = deployment };
        }
 /// <summary>
 /// Used to delete a deployment in a respective slot 
 /// </summary>
 /// <param name="slot">Either production or staging</param>
 public void DeleteDeployment(DeploymentSlot slot = DeploymentSlot.Production)
 {
     var deleteDeployment = new DeleteDeploymentCommand(Name, slot)
     {
         Certificate = ManagementCertificate,
         SubscriptionId = SubscriptionId
     };
     deleteDeployment.Execute();
 }
 /// <summary>
 ///     Reboot worker role
 /// </summary>
 /// <param name="hostedServiceName"></param>
 /// <param name="slot"></param>
 /// <param name="roleInstanceName"></param>
 public void RebootDeploymentRoleInstanceBySlot(string hostedServiceName, DeploymentSlot slot, string roleInstanceName)
 {
     ComputeManagementClient.Deployments.RebootRoleInstanceByDeploymentSlotAsync(
         hostedServiceName,
         slot,
         roleInstanceName,
         new CancellationToken());
 }