/// <summary> /// Creates cloud service if it does not exist. /// </summary> /// <param name="name">The cloud service name</param> /// <param name="label">The cloud service label</param> public void CreateCloudServiceIfNotExist( string name, string label = null, string location = null, string affinityGroup = null) { if (!CloudServiceExists(name)) { WriteVerboseWithTimestamp(Resources.PublishCreatingServiceMessage); CreateHostedServiceInput cloudServiceInput = new CreateHostedServiceInput { ServiceName = name, Label = string.IsNullOrEmpty(label) ? name : label }; if (!string.IsNullOrEmpty(affinityGroup)) { cloudServiceInput.AffinityGroup = affinityGroup; } else { location = string.IsNullOrEmpty(location) ? GetDefaultLocation() : location; cloudServiceInput.Location = location; } ServiceManagementChannel.CreateHostedService(subscriptionId, cloudServiceInput); WriteVerboseWithTimestamp(Resources.PublishCreatedServiceMessage, name); } }
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); }
/// <summary> /// Creates storage service if it does not exist. /// </summary> /// <param name="name">The storage service name</param> /// <param name="label">The storage service label</param> /// <param name="location">The location name. If not provided default one will be used</param> /// <param name="affinityGroup">The affinity group name</param> public void CreateStorageServiceIfNotExist( string name, string label = null, string location = null, string affinityGroup = null) { if (!StorageServiceExists(name)) { CreateStorageServiceInput storageServiceInput = new CreateStorageServiceInput { ServiceName = name, Label = label, }; if (!string.IsNullOrEmpty(affinityGroup)) { storageServiceInput.AffinityGroup = affinityGroup; } else { location = string.IsNullOrEmpty(location) ? GetDefaultLocation() : location; storageServiceInput.Location = location; } CallSync(() => ServiceManagementChannel.CreateStorageService(subscriptionId, storageServiceInput)); } }
private void CreateDeployment(PublishContext context) { CreateDeploymentInput deploymentInput = new CreateDeploymentInput { PackageUrl = UploadPackage(context), Configuration = General.GetConfiguration(context.ConfigPath), Label = context.ServiceName, Name = context.DeploymentName, StartDeployment = true, }; WriteVerboseWithTimestamp(Resources.PublishStartingMessage); CertificateList uploadedCertificates = ServiceManagementChannel.ListCertificates( subscriptionId, context.ServiceName); AddCertificates(uploadedCertificates, context); ServiceManagementChannel.CreateOrUpdateDeployment( subscriptionId, context.ServiceName, context.ServiceSettings.Slot, deploymentInput); }
private void DeleteDeploymentIfExists(string name, string slot) { if (DeploymentExists(name, slot)) { WriteVerboseWithTimestamp(Resources.RemoveDeploymentWaitMessage, slot, name); CallSync(() => ServiceManagementChannel.DeleteDeploymentBySlot(subscriptionId, name, slot)); } }
/// <summary> /// Gets complete information of a storage service. /// </summary> /// <param name="name">The storage service name</param> /// <returns>The storage service instance</returns> public StorageService GetStorageService(string name) { StorageService storageService = ServiceManagementChannel.GetStorageService(subscriptionId, name); StorageService storageServiceKeys = ServiceManagementChannel.GetStorageKeys(subscriptionId, name); storageService.StorageServiceKeys = storageServiceKeys.StorageServiceKeys; return(storageService); }
/// <summary> /// Removes all deployments in the given cloud service and the service itself. /// </summary> /// <param name="name">The cloud service name</param> public void RemoveCloudService(string name) { HostedService cloudService = GetCloudService(name); DeleteDeploymentIfExists(cloudService.ServiceName, DeploymentSlotType.Production); DeleteDeploymentIfExists(cloudService.ServiceName, DeploymentSlotType.Staging); WriteVerboseWithTimestamp(string.Format(Resources.RemoveAzureServiceWaitMessage, cloudService.ServiceName)); CallSync(() => ServiceManagementChannel.DeleteHostedService(subscriptionId, cloudService.ServiceName)); }
private void SetApplicationDiagnosticsSettings( string name, WebsiteDiagnosticOutput output, bool setFlag, Dictionary <DiagnosticProperties, object> properties = null) { Site website = GetWebsite(name); using (HttpClient client = CreateHttpClient(website.Name)) { DiagnosticsSettings diagnosticsSettings = GetApplicationDiagnosticsSettings(website.Name); switch (output) { case WebsiteDiagnosticOutput.FileSystem: diagnosticsSettings.AzureDriveTraceEnabled = setFlag; diagnosticsSettings.AzureDriveTraceLevel = setFlag ? (LogEntryType)properties[DiagnosticProperties.LogLevel] : diagnosticsSettings.AzureDriveTraceLevel; break; case WebsiteDiagnosticOutput.StorageTable: diagnosticsSettings.AzureTableTraceEnabled = setFlag; if (setFlag) { const string storageTableName = "CLOUD_STORAGE_ACCOUNT"; string storageAccountName = (string)properties[DiagnosticProperties.StorageAccountName]; StorageService storageService = ServiceManagementChannel.GetStorageKeys( SubscriptionId, storageAccountName); StorageCredentials credentials = new StorageCredentials( storageAccountName, storageService.StorageServiceKeys.Primary); CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(credentials, false); string connectionString = cloudStorageAccount.ToString(true); AddAppSetting(website.Name, storageTableName, connectionString); diagnosticsSettings.AzureTableTraceLevel = setFlag ? (LogEntryType)properties[DiagnosticProperties.LogLevel] : diagnosticsSettings.AzureTableTraceLevel; } break; default: throw new ArgumentException(); } JObject json = new JObject(); json[UriElements.AzureDriveTraceEnabled] = diagnosticsSettings.AzureDriveTraceEnabled; json[UriElements.AzureDriveTraceLevel] = JToken.FromObject(diagnosticsSettings.AzureDriveTraceLevel); json[UriElements.AzureTableTraceEnabled] = diagnosticsSettings.AzureTableTraceEnabled; json[UriElements.AzureTableTraceLevel] = JToken.FromObject(diagnosticsSettings.AzureTableTraceLevel); client.PostAsJsonAsync(UriElements.DiagnosticsSettings, json, Logger); } }
private HostedService GetCloudService(string name) { name = GetCloudServiceName(name); try { return(ServiceManagementChannel.GetHostedServiceWithDetails(subscriptionId, name, true)); } catch { throw new Exception(string.Format(Resources.ServiceDoesNotExist, name)); } }
/// <summary> /// Checks if a cloud service exists or not. /// </summary> /// <param name="name">The cloud service name</param> /// <returns>True if exists, false otherwise</returns> public bool CloudServiceExists(string name) { HostedService cloudService = null; try { cloudService = ServiceManagementChannel.GetHostedServiceWithDetails(subscriptionId, name, true); } catch { return(false); } return(cloudService != null); }
private void SetCloudServiceState(string name, string slot, CloudServiceState state) { HostedService cloudService = GetCloudService(name); slot = GetSlot(slot); VerifyDeploymentExists(cloudService, slot); ServiceManagementChannel.UpdateDeploymentStatusBySlot( subscriptionId, cloudService.ServiceName, slot, new UpdateDeploymentStatusInput() { Status = state == CloudServiceState.Start ? DeploymentStatus.Running : DeploymentStatus.Suspended } ); }
/// <summary> /// Gets complete information of a storage service. /// </summary> /// <param name="name">The storage service name</param> /// <returns>The storage service instance</returns> public StorageService GetStorageService(string name) { StorageService storageService = null; try { storageService = ServiceManagementChannel.GetStorageService(subscriptionId, name); StorageService storageServiceKeys = ServiceManagementChannel.GetStorageKeys(subscriptionId, name); storageService.StorageServiceKeys = storageServiceKeys.StorageServiceKeys; } catch { throw new Exception(string.Format(Resources.StorageAccountNotFound, name)); } return(storageService); }
/// <summary> /// Waits for the given operation id until it's done. /// </summary> /// <param name="operationId">The operation id</param> public void WaitForOperation(string operationId) { Operation operation = new Operation(); do { operation = ServiceManagementChannel.GetOperationStatus(subscriptionId, operationId); Thread.Sleep(SleepDuration); }while (operation.Status == OperationState.InProgress); if (operation.Status == OperationState.Failed) { throw new Exception(string.Format( Resources.OperationFailedMessage, operation.Error.Message, operation.Error.Code)); } }
/// <summary> /// Checks if the provided storage service exists under the subscription or not. /// </summary> /// <param name="name">The storage service name</param> /// <returns>True if exists, false otherwise</returns> public bool StorageServiceExists(string name) { StorageService storageService = null; try { storageService = ServiceManagementChannel.GetStorageService(subscriptionId, name); } catch (EndpointNotFoundException) { // Don't write error message. This catch block is used to // detect that there's no such endpoint which indicates that // the storage account doesn't exist. return(false); } return(storageService != null); }
private void AddCertificates(CertificateList uploadedCertificates, PublishContext context) { string name = context.ServiceName; AzureService cloudServiceProject = new AzureService(context.RootPath, null); if (cloudServiceProject.Components.CloudConfig.Role != null) { foreach (ConfigCertificate certElement in cloudServiceProject.Components.CloudConfig.Role. SelectMany(r => r.Certificates ?? new ConfigCertificate[0]).Distinct()) { if (uploadedCertificates == null || (uploadedCertificates.Count(c => c.Thumbprint.Equals( certElement.thumbprint, StringComparison.OrdinalIgnoreCase)) < 1)) { X509Certificate2 cert = General.GetCertificateFromStore(certElement.thumbprint); CertificateFile certFile = null; try { certFile = new CertificateFile { Data = Convert.ToBase64String(cert.Export(X509ContentType.Pfx, string.Empty)), Password = string.Empty, CertificateFormat = "pfx" }; } catch (CryptographicException exception) { throw new ArgumentException(string.Format( Resources.CertificatePrivateKeyAccessError, certElement.name), exception); } CallSync(() => ServiceManagementChannel.AddCertificates(subscriptionId, name, certFile)); } } } }
private void UpgradeDeployment(PublishContext context) { UpgradeDeploymentInput upgradeDeploymentInput = new UpgradeDeploymentInput { PackageUrl = UploadPackage(context), Configuration = General.GetConfiguration(context.ConfigPath), Label = context.ServiceName, Mode = UpgradeType.Auto }; WriteVerboseWithTimestamp(Resources.PublishUpgradingMessage); CertificateList uploadedCertificates = ServiceManagementChannel.ListCertificates( subscriptionId, context.ServiceName); AddCertificates(uploadedCertificates, context); ServiceManagementChannel.UpgradeDeploymentBySlot( subscriptionId, context.ServiceName, context.ServiceSettings.Slot, upgradeDeploymentInput); }
/// <summary> /// Publishes a service project on Windows Azure. /// </summary> /// <param name="name">The cloud service name</param> /// <param name="slot">The deployment slot</param> /// <param name="location">The deployment location</param> /// <param name="affinityGroup">The deployment affinity group</param> /// <param name="storageAccount">The storage account to store the package</param> /// <param name="deploymentName">The deployment name</param> /// <param name="launch">Launch the service after publishing</param> /// <returns>The created deployment</returns> public Deployment PublishCloudService( string name = null, string slot = null, string location = null, string affinityGroup = null, string storageAccount = null, string deploymentName = null, bool launch = false) { // Initialize publish context PublishContext context = CreatePublishContext( name, slot, location, affinityGroup, storageAccount, deploymentName); WriteVerbose(string.Format(Resources.PublishServiceStartMessage, context.ServiceName)); // Set package runtime information WriteVerboseWithTimestamp(Resources.RuntimeDeploymentStart, context.ServiceName); PrepareCloudServicePackagesRuntime(context); // Verify storage account exists WriteVerboseWithTimestamp( Resources.PublishVerifyingStorageMessage, context.ServiceSettings.StorageServiceName); CreateStorageServiceIfNotExist( context.ServiceSettings.StorageServiceName, context.ServiceName, context.ServiceSettings.Location, context.ServiceSettings.AffinityGroup); // Update cache worker roles configuration WriteVerboseWithTimestamp( Resources.PublishPreparingDeploymentMessage, context.ServiceName, subscriptionId); UpdateCacheWorkerRolesCloudConfiguration(context); // Create cloud package AzureTool.Validate(); if (File.Exists(context.PackagePath)) { File.Delete(context.PackagePath); } AzureService cloudServiceProject = new AzureService(context.RootPath, null); string unused; cloudServiceProject.CreatePackage(DevEnv.Cloud, out unused, out unused); // Publish cloud service WriteVerboseWithTimestamp(Resources.PublishConnectingMessage); CreateCloudServiceIfNotExist( context.ServiceName, affinityGroup: context.ServiceSettings.AffinityGroup, location: context.ServiceSettings.Location); if (DeploymentExists(context.ServiceName, context.ServiceSettings.Slot)) { // Upgrade the deployment UpgradeDeployment(context); } else { // Create new deployment CreateDeployment(context); } // Get the deployment id and show it. WriteVerboseWithTimestamp(Resources.PublishCreatedDeploymentMessage, GetDeploymentId(context)); // Verify the deployment succeeded by checking that each of the roles are running VerifyDeployment(context); // Get object of the published deployment Deployment deployment = ServiceManagementChannel.GetDeploymentBySlot( subscriptionId, context.ServiceName, context.ServiceSettings.Slot); if (launch) { General.LaunchWebPage(deployment.Url.ToString()); } return(deployment); }
/// <summary> /// Gets the default subscription location. /// </summary> /// <returns>The location name</returns> public string GetDefaultLocation() { LocationList locations = ServiceManagementChannel.ListLocations(subscriptionId); return(locations.First().Name); }
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)); } }