private static void RefreshCredentials(string source, SubscriptionListOperationResponse.Subscription subscription, SubscriptionCloudCredentials credentials) { var tokenCloudCredentials = credentials as TokenCloudCredentials; if (tokenCloudCredentials != null) { var newCredentials = GetCredentials(source, subscription); tokenCloudCredentials.Token = newCredentials.Token; } }
private static async Task CleanupExistingExtensions(string source, SubscriptionListOperationResponse.Subscription subscription, HostedServiceListResponse.HostedService service, ComputeManagementClient computeClient, ExtensionImage availableDiagnosticsExtension) { // Get whatever is currently on Production Logger.InfoFormat("[" + source + "] " + "Retrieving current deployment details and currently used extensions..."); DeploymentGetResponse currentProductionSlotDetails = null, currentStagingSlotDetails = null; var details = computeClient.HostedServices.GetDetailed(service.ServiceName); if (details.Deployments.Where(s => s.DeploymentSlot == DeploymentSlot.Production).Any()) { currentProductionSlotDetails = await computeClient.Deployments.GetBySlotAsync(service.ServiceName, DeploymentSlot.Production); } if (details.Deployments.Where(s => s.DeploymentSlot == DeploymentSlot.Staging).Any()) { currentStagingSlotDetails = await computeClient.Deployments.GetBySlotAsync(service.ServiceName, DeploymentSlot.Staging); } // Compile a list of diagnostic id's still in use List <string> diagIdsInUse = new List <string>(); if (currentProductionSlotDetails != null && currentProductionSlotDetails.ExtensionConfiguration != null) { diagIdsInUse.AddRange(currentProductionSlotDetails.ExtensionConfiguration.AllRoles.Select(s => s.Id)); diagIdsInUse.AddRange(currentProductionSlotDetails.ExtensionConfiguration.NamedRoles.SelectMany(s => s.Extensions).Select(s => s.Id)); } if (currentStagingSlotDetails != null && currentStagingSlotDetails.ExtensionConfiguration != null) { diagIdsInUse.AddRange(currentStagingSlotDetails.ExtensionConfiguration.AllRoles.Select(s => s.Id)); diagIdsInUse.AddRange(currentStagingSlotDetails.ExtensionConfiguration.NamedRoles.SelectMany(s => s.Extensions).Select(s => s.Id)); } // Check if diag extension already exists for this service. If so, delete it. Logger.InfoFormat("[" + source + "] " + "Retrieving all extensions for {0}...", service.ServiceName); var currentExtensions = await computeClient.HostedServices.ListExtensionsAsync(service.ServiceName); foreach (var currentDiagExtension in currentExtensions.Where(d => d.Type == availableDiagnosticsExtension.Type)) { if (diagIdsInUse.Contains(currentDiagExtension.Id)) { Logger.InfoFormat("[" + source + "] " + "Skip deleting diagnostics extension {0}, because it is in use by the deployment", currentDiagExtension.Id); } else { Logger.InfoFormat("[" + source + "] " + "Deleting unused diagnostics extension named {0}...", currentDiagExtension.Id); try { var deleteOperation = await computeClient.HostedServices.DeleteExtensionAsync(service.ServiceName, currentDiagExtension.Id); await WaitForOperationAsync(source, subscription, computeClient, deleteOperation.RequestId); } catch (Exception) { Logger.ErrorFormat("[" + source + "] " + "Couldn't delete extension {0}, might be in use...", currentDiagExtension.Id); } } } }
public static TokenCloudCredentials GetCredentials(string source, SubscriptionListOperationResponse.Subscription subscription = null) { TokenCloudCredentials token = null; if (subscription == null) { token = new TokenCloudCredentials(GetAuthentication(source).AccessToken); } else { token = new TokenCloudCredentials(subscription.SubscriptionId, GetAuthentication(source, subscription.ActiveDirectoryTenantId).AccessToken); } return(token); }
private static async Task WaitForOperationAsync(string source, SubscriptionListOperationResponse.Subscription subscription, ComputeManagementClient client, string requestId) { var statusResponse = await client.GetOperationStatusAsync(requestId); while (statusResponse.Status == OperationStatus.InProgress) { Logger.InfoFormat("Waiting for operation to finish..."); await Task.Delay(5000); RefreshCredentials(source, subscription, client.Credentials); statusResponse = await client.GetOperationStatusAsync(requestId); } if (statusResponse.Status == OperationStatus.Failed) { throw new CloudException("Operation failed with code " + statusResponse.Error.Code + ": " + statusResponse.Error.Message); } }
/// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Subscriptions.Models.SubscriptionListOperationResponse> ListAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); Tracing.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = "/subscriptions"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-08-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result SubscriptionListOperationResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new SubscriptionListOperationResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement subscriptionsElement = responseDoc.Element(XName.Get("Subscriptions", "http://schemas.microsoft.com/windowsazure")); if (subscriptionsElement != null) { if (subscriptionsElement != null) { result.Subscriptions = new List <SubscriptionListOperationResponse.Subscription>(); foreach (XElement subscriptionsElement2 in subscriptionsElement.Elements(XName.Get("Subscription", "http://schemas.microsoft.com/windowsazure"))) { SubscriptionListOperationResponse.Subscription subscriptionInstance = new SubscriptionListOperationResponse.Subscription(); result.Subscriptions.Add(subscriptionInstance); XElement subscriptionIDElement = subscriptionsElement2.Element(XName.Get("SubscriptionID", "http://schemas.microsoft.com/windowsazure")); if (subscriptionIDElement != null) { string subscriptionIDInstance = subscriptionIDElement.Value; subscriptionInstance.SubscriptionId = subscriptionIDInstance; } XElement subscriptionNameElement = subscriptionsElement2.Element(XName.Get("SubscriptionName", "http://schemas.microsoft.com/windowsazure")); if (subscriptionNameElement != null) { string subscriptionNameInstance = subscriptionNameElement.Value; subscriptionInstance.SubscriptionName = subscriptionNameInstance; } XElement subscriptionStatusElement = subscriptionsElement2.Element(XName.Get("SubscriptionStatus", "http://schemas.microsoft.com/windowsazure")); if (subscriptionStatusElement != null) { SubscriptionStatus subscriptionStatusInstance = ((SubscriptionStatus)Enum.Parse(typeof(SubscriptionStatus), subscriptionStatusElement.Value, true)); subscriptionInstance.SubscriptionStatus = subscriptionStatusInstance; } XElement accountAdminLiveEmailIdElement = subscriptionsElement2.Element(XName.Get("AccountAdminLiveEmailId", "http://schemas.microsoft.com/windowsazure")); if (accountAdminLiveEmailIdElement != null) { string accountAdminLiveEmailIdInstance = accountAdminLiveEmailIdElement.Value; subscriptionInstance.AccountAdminLiveEmailId = accountAdminLiveEmailIdInstance; } XElement serviceAdminLiveEmailIdElement = subscriptionsElement2.Element(XName.Get("ServiceAdminLiveEmailId", "http://schemas.microsoft.com/windowsazure")); if (serviceAdminLiveEmailIdElement != null) { string serviceAdminLiveEmailIdInstance = serviceAdminLiveEmailIdElement.Value; subscriptionInstance.ServiceAdminLiveEmailId = serviceAdminLiveEmailIdInstance; } XElement maxCoreCountElement = subscriptionsElement2.Element(XName.Get("MaxCoreCount", "http://schemas.microsoft.com/windowsazure")); if (maxCoreCountElement != null) { int maxCoreCountInstance = int.Parse(maxCoreCountElement.Value, CultureInfo.InvariantCulture); subscriptionInstance.MaximumCoreCount = maxCoreCountInstance; } XElement maxStorageAccountsElement = subscriptionsElement2.Element(XName.Get("MaxStorageAccounts", "http://schemas.microsoft.com/windowsazure")); if (maxStorageAccountsElement != null) { int maxStorageAccountsInstance = int.Parse(maxStorageAccountsElement.Value, CultureInfo.InvariantCulture); subscriptionInstance.MaximumStorageAccounts = maxStorageAccountsInstance; } XElement maxHostedServicesElement = subscriptionsElement2.Element(XName.Get("MaxHostedServices", "http://schemas.microsoft.com/windowsazure")); if (maxHostedServicesElement != null) { int maxHostedServicesInstance = int.Parse(maxHostedServicesElement.Value, CultureInfo.InvariantCulture); subscriptionInstance.MaximumHostedServices = maxHostedServicesInstance; } XElement currentCoreCountElement = subscriptionsElement2.Element(XName.Get("CurrentCoreCount", "http://schemas.microsoft.com/windowsazure")); if (currentCoreCountElement != null) { int currentCoreCountInstance = int.Parse(currentCoreCountElement.Value, CultureInfo.InvariantCulture); subscriptionInstance.CurrentCoreCount = currentCoreCountInstance; } XElement currentStorageAccountsElement = subscriptionsElement2.Element(XName.Get("CurrentStorageAccounts", "http://schemas.microsoft.com/windowsazure")); if (currentStorageAccountsElement != null) { int currentStorageAccountsInstance = int.Parse(currentStorageAccountsElement.Value, CultureInfo.InvariantCulture); subscriptionInstance.CurrentStorageAccounts = currentStorageAccountsInstance; } XElement currentHostedServicesElement = subscriptionsElement2.Element(XName.Get("CurrentHostedServices", "http://schemas.microsoft.com/windowsazure")); if (currentHostedServicesElement != null) { int currentHostedServicesInstance = int.Parse(currentHostedServicesElement.Value, CultureInfo.InvariantCulture); subscriptionInstance.CurrentHostedServices = currentHostedServicesInstance; } XElement maxVirtualNetworkSitesElement = subscriptionsElement2.Element(XName.Get("MaxVirtualNetworkSites", "http://schemas.microsoft.com/windowsazure")); if (maxVirtualNetworkSitesElement != null) { int maxVirtualNetworkSitesInstance = int.Parse(maxVirtualNetworkSitesElement.Value, CultureInfo.InvariantCulture); subscriptionInstance.MaximumVirtualNetworkSites = maxVirtualNetworkSitesInstance; } XElement maxLocalNetworkSitesElement = subscriptionsElement2.Element(XName.Get("MaxLocalNetworkSites", "http://schemas.microsoft.com/windowsazure")); if (maxLocalNetworkSitesElement != null) { int maxLocalNetworkSitesInstance = int.Parse(maxLocalNetworkSitesElement.Value, CultureInfo.InvariantCulture); subscriptionInstance.MaximumLocalNetworkSites = maxLocalNetworkSitesInstance; } XElement maxDnsServersElement = subscriptionsElement2.Element(XName.Get("MaxDnsServers", "http://schemas.microsoft.com/windowsazure")); if (maxDnsServersElement != null) { int maxDnsServersInstance = int.Parse(maxDnsServersElement.Value, CultureInfo.InvariantCulture); subscriptionInstance.MaximumDnsServers = maxDnsServersInstance; } XElement maxExtraVIPCountElement = subscriptionsElement2.Element(XName.Get("MaxExtraVIPCount", "http://schemas.microsoft.com/windowsazure")); if (maxExtraVIPCountElement != null) { int maxExtraVIPCountInstance = int.Parse(maxExtraVIPCountElement.Value, CultureInfo.InvariantCulture); subscriptionInstance.MaximumExtraVirtualIPCount = maxExtraVIPCountInstance; } XElement aADTenantIDElement = subscriptionsElement2.Element(XName.Get("AADTenantID", "http://schemas.microsoft.com/windowsazure")); if (aADTenantIDElement != null) { string aADTenantIDInstance = aADTenantIDElement.Value; subscriptionInstance.ActiveDirectoryTenantId = aADTenantIDInstance; } XElement createdTimeElement = subscriptionsElement2.Element(XName.Get("CreatedTime", "http://schemas.microsoft.com/windowsazure")); if (createdTimeElement != null) { DateTime createdTimeInstance = DateTime.Parse(createdTimeElement.Value, CultureInfo.InvariantCulture); subscriptionInstance.Created = createdTimeInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
public static async Task DownloadDeploymentAsync(string source, SubscriptionListOperationResponse.Subscription subscription, HostedServiceListResponse.HostedService service, DeploymentSlot slot, StorageAccount temporaryStorage, string downloadToPath, bool warnInsteadOfThrow = false) { Logger.InfoFormat("[" + source + "] " + "Preparing to download {0}/{1}...", service.ServiceName, slot); var computeClient = new ComputeManagementClient(GetCredentials(source, subscription)); var storageClient = new StorageManagementClient(GetCredentials(source, subscription)); Logger.InfoFormat("[" + source + "] " + "Checking existing deployment in {0} slot...", slot); var detailedService = await computeClient.HostedServices.GetDetailedAsync(service.ServiceName); if (!detailedService.Deployments.Where(s => s.DeploymentSlot == slot).Any()) { if (warnInsteadOfThrow) { Logger.WarnFormat("[" + source + "] " + "No deployment found in selected slot, not downloading..."); return; } else { throw new ApplicationException("No deployment found in selected slot"); } } Logger.InfoFormat("[" + source + "] " + "Getting current diagnostics extension data (if any)..."); var detailedSlot = await computeClient.Deployments.GetBySlotAsync(service.ServiceName, slot); string pubConfig = null; if (detailedSlot.ExtensionConfiguration != null) { foreach (var ext in detailedSlot.ExtensionConfiguration.AllRoles.Union(detailedSlot.ExtensionConfiguration.NamedRoles.SelectMany(s => s.Extensions))) { Logger.InfoFormat("[" + source + "] " + "Fetching extension with id {0}...", ext.Id); var extension = await computeClient.HostedServices.GetExtensionAsync(service.ServiceName, ext.Id); if (extension.Type == "PaaSDiagnostics") { Logger.InfoFormat("[" + source + "] " + "Found extension of type {0}, which should be the diagnostics PubConfig...", extension.Type); pubConfig = extension.PublicConfiguration; } } } if (pubConfig == null) { Logger.InfoFormat("[" + source + "] " + "No PaaSDiagnostics extension found..."); } Logger.InfoFormat("[" + source + "] " + "Preparing temp storage account {0}...", temporaryStorage.Name); var keys = await storageClient.StorageAccounts.GetKeysAsync(temporaryStorage.Name); var csa = new CloudStorageAccount(new StorageCredentials(temporaryStorage.Name, keys.PrimaryKey), true); var client = csa.CreateCloudBlobClient(); var container = client.GetContainerReference("acd-temp-" + Guid.NewGuid().ToString("N").ToLower()); Logger.InfoFormat("[" + source + "] " + "Creating temp container {0}...", container.Name); await container.CreateIfNotExistsAsync(); Logger.InfoFormat("[" + source + "] " + "Downloading package to storage account {0}...", temporaryStorage.Name); var getPackageOperation = await computeClient.Deployments.BeginGettingPackageBySlotAsync(service.ServiceName, slot, new DeploymentGetPackageParameters { ContainerUri = container.Uri }); await WaitForOperationAsync(source, subscription, computeClient, getPackageOperation.RequestId); Logger.InfoFormat("[" + source + "] " + "Downloading from storage to {0}...", downloadToPath); var result = await container.ListBlobsSegmentedAsync(null); var prefix = string.Format("{0} {1} {2}", DateTime.Now.ToString("yyyy-MM-dd HH-mm"), service.ServiceName, slot); foreach (var item in result.Results) { var cloudblob = client.GetBlobReferenceFromServer(item.StorageUri); string filename = prefix + " " + cloudblob.Name; Logger.Info("[" + source + "] " + "Downloading: " + filename); await cloudblob.DownloadToFileAsync(Path.Combine(downloadToPath, filename), FileMode.Create); } if (pubConfig != null) { Logger.InfoFormat("[" + source + "] " + "Writing PubConfig to {0}...", prefix + ".PubConfig.xml"); string pubconfigFilename = Path.Combine(downloadToPath, prefix + ".PubConfig.xml"); File.WriteAllText(pubconfigFilename, pubConfig); } Logger.Info("[" + source + "] " + "Cleaning up temp storage..."); await container.DeleteAsync(); Logger.Info("[" + source + "] " + "Package download succesful"); }
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 static async Task <StorageAccountListResponse> GetStorageAccountsAsync(string source, SubscriptionListOperationResponse.Subscription subscription) { return(await GetCachedAsync(source, "StorageAccounts_" + subscription.SubscriptionId, async() => { var storageClient = new StorageManagementClient(GetCredentials(source, subscription)); Logger.Info("[" + source + "] " + "Retrieving storage accounts..."); return await storageClient.StorageAccounts.ListAsync(); })); }
public static async Task <HostedServiceListResponse> GetCloudservicesAsync(string source, SubscriptionListOperationResponse.Subscription subscription) { return(await GetCachedAsync(source, "CloudServices_" + subscription.SubscriptionId, async() => { var computeClient = new ComputeManagementClient(GetCredentials(source, subscription)); Logger.Info("[" + source + "] " + "Retrieving hosted services..."); return await computeClient.HostedServices.ListAsync(); })); }
private void SetMockData() { commonTenant = new TenantIdDescription { Id = "Common", TenantId = "Common" }; guestTenant = new TenantIdDescription { Id = "Guest", TenantId = "Guest" }; rdfeSubscription1 = new RDFESubscription { SubscriptionId = "16E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E", SubscriptionName = "RdfeSub1", SubscriptionStatus = Microsoft.WindowsAzure.Subscriptions.Models.SubscriptionStatus.Active, ActiveDirectoryTenantId = "Common" }; rdfeSubscription2 = new RDFESubscription { SubscriptionId = "26E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E", SubscriptionName = "RdfeSub2", SubscriptionStatus = Microsoft.WindowsAzure.Subscriptions.Models.SubscriptionStatus.Active, ActiveDirectoryTenantId = "Common" }; guestRdfeSubscription = new RDFESubscription { SubscriptionId = "26E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1C", SubscriptionName = "RdfeSub2", SubscriptionStatus = Microsoft.WindowsAzure.Subscriptions.Models.SubscriptionStatus.Active, ActiveDirectoryTenantId = "Guest" }; csmSubscription1 = new CSMSubscription { Id = "Subscriptions/36E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E", DisplayName = "CsmSub1", State = "Active", SubscriptionId = "36E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E" }; csmSubscription1withDuplicateId = new CSMSubscription { Id = "Subscriptions/16E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E", DisplayName = "RdfeSub1", State = "Active", SubscriptionId = "16E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E" }; csmSubscription2 = new CSMSubscription { Id = "Subscriptions/46E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E", DisplayName = "CsmSub2", State = "Active", SubscriptionId = "46E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E" }; guestCsmSubscription = new CSMSubscription { Id = "Subscriptions/76E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1D", DisplayName = "CsmGuestSub", State = "Active", SubscriptionId = "76E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1D" }; azureSubscription1 = new AzureSubscription { Id = new Guid("56E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"), Name = "LocalSub1", Environment = "Test", Account = "test", Properties = new Dictionary<AzureSubscription.Property, string> { { AzureSubscription.Property.Default, "True" } } }; azureSubscription2 = new AzureSubscription { Id = new Guid("66E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"), Name = "LocalSub2", Environment = "Test", Account = "test" }; azureSubscription3withoutUser = new AzureSubscription { Id = new Guid("76E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"), Name = "LocalSub3", Environment = "Test", }; azureEnvironment = new AzureEnvironment { Name = "Test", Endpoints = new Dictionary<AzureEnvironment.Endpoint, string> { { AzureEnvironment.Endpoint.ServiceManagement, "https://umapi.rdfetest.dnsdemo4.com:8443/" }, { AzureEnvironment.Endpoint.ManagementPortalUrl, "https://windows.azure-test.net" }, { AzureEnvironment.Endpoint.AdTenant, "https://login.windows-ppe.net/" }, { AzureEnvironment.Endpoint.ActiveDirectory, "https://login.windows-ppe.net/" }, { AzureEnvironment.Endpoint.Gallery, "https://current.gallery.azure-test.net" }, { AzureEnvironment.Endpoint.ResourceManager, "https://api-current.resources.windows-int.net/" }, } }; azureAccount = new AzureAccount { Id = "test", Type = AzureAccount.AccountType.User, Properties = new Dictionary<AzureAccount.Property, string> { { AzureAccount.Property.Subscriptions, azureSubscription1.Id + "," + azureSubscription2.Id } } }; newProfileDataPath = System.IO.Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile); oldProfileDataPath = System.IO.Path.Combine(AzureSession.ProfileDirectory, AzureSession.OldProfileFile); oldProfileDataPathError = System.IO.Path.Combine(AzureSession.ProfileDirectory, AzureSession.OldProfileFileBackup); oldProfileData = @"<?xml version=""1.0"" encoding=""utf-8""?> <ProfileData xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/Microsoft.Azure.Common.Extensions""> <DefaultEnvironmentName>AzureCloud</DefaultEnvironmentName> <Environments> <AzureEnvironmentData> <ActiveDirectoryServiceEndpointResourceId>https://management.core.windows.net/</ActiveDirectoryServiceEndpointResourceId> <AdTenantUrl>https://login.windows-ppe.net/</AdTenantUrl> <CommonTenantId>Common</CommonTenantId> <GalleryEndpoint>https://current.gallery.azure-test.net</GalleryEndpoint> <ManagementPortalUrl>http://go.microsoft.com/fwlink/?LinkId=254433</ManagementPortalUrl> <Name>Current</Name> <PublishSettingsFileUrl>d:\Code\azure.publishsettings</PublishSettingsFileUrl> <ResourceManagerEndpoint>https://api-current.resources.windows-int.net/</ResourceManagerEndpoint> <ServiceEndpoint>https://umapi.rdfetest.dnsdemo4.com:8443/</ServiceEndpoint> <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix> <StorageEndpointSuffix i:nil=""true"" /> <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix> </AzureEnvironmentData> <AzureEnvironmentData> <ActiveDirectoryServiceEndpointResourceId>https://management.core.windows.net/</ActiveDirectoryServiceEndpointResourceId> <AdTenantUrl>https://login.windows-ppe.net/</AdTenantUrl> <CommonTenantId>Common</CommonTenantId> <GalleryEndpoint>https://df.gallery.azure-test.net</GalleryEndpoint> <ManagementPortalUrl>https://windows.azure-test.net</ManagementPortalUrl> <Name>Dogfood</Name> <PublishSettingsFileUrl>https://auxnext.windows.azure-test.net/publishsettings/index</PublishSettingsFileUrl> <ResourceManagerEndpoint>https://api-dogfood.resources.windows-int.net</ResourceManagerEndpoint> <ServiceEndpoint>https://management-preview.core.windows-int.net/</ServiceEndpoint> <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix> <StorageEndpointSuffix i:nil=""true"" /> <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix> </AzureEnvironmentData> </Environments> <Subscriptions> <AzureSubscriptionData> <ActiveDirectoryEndpoint i:nil=""true"" /> <ActiveDirectoryServiceEndpointResourceId i:nil=""true"" /> <ActiveDirectoryTenantId i:nil=""true"" /> <ActiveDirectoryUserId i:nil=""true"" /> <CloudStorageAccount i:nil=""true"" /> <GalleryEndpoint i:nil=""true"" /> <IsDefault>true</IsDefault> <LoginType i:nil=""true"" /> <ManagementCertificate i:nil=""true""/> <ManagementEndpoint>https://management.core.windows.net/</ManagementEndpoint> <Name>Test</Name> <RegisteredResourceProviders xmlns:d4p1=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"" /> <ResourceManagerEndpoint i:nil=""true"" /> <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix> <SubscriptionId>06E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E</SubscriptionId> <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix> </AzureSubscriptionData> <AzureSubscriptionData> <ActiveDirectoryEndpoint i:nil=""true"" /> <ActiveDirectoryServiceEndpointResourceId i:nil=""true"" /> <ActiveDirectoryTenantId>123</ActiveDirectoryTenantId> <ActiveDirectoryUserId>[email protected]</ActiveDirectoryUserId> <CloudStorageAccount i:nil=""true"" /> <GalleryEndpoint i:nil=""true"" /> <IsDefault>true</IsDefault> <LoginType i:nil=""true"" /> <ManagementCertificate i:nil=""true""/> <ManagementEndpoint>https://management-preview.core.windows-int.net/</ManagementEndpoint> <Name>Test 2</Name> <RegisteredResourceProviders xmlns:d4p1=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"" /> <ResourceManagerEndpoint i:nil=""true"" /> <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix> <SubscriptionId>06E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1F</SubscriptionId> <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix> </AzureSubscriptionData> <AzureSubscriptionData> <ActiveDirectoryEndpoint>https://login.windows.net/</ActiveDirectoryEndpoint> <ActiveDirectoryServiceEndpointResourceId>https://management.core.windows.net/</ActiveDirectoryServiceEndpointResourceId> <ActiveDirectoryTenantId>72f988bf-86f1-41af-91ab-2d7cd011db47</ActiveDirectoryTenantId> <ActiveDirectoryUserId>[email protected]</ActiveDirectoryUserId> <CloudStorageAccount i:nil=""true"" /> <GalleryEndpoint i:nil=""true"" /> <IsDefault>false</IsDefault> <LoginType i:nil=""true"" /> <ManagementCertificate>3AF24D48B97730E5C4C9CCB12397B5E046F79E09</ManagementCertificate> <ManagementEndpoint>https://management.core.windows.net/</ManagementEndpoint> <Name>Test 3</Name> <RegisteredResourceProviders xmlns:d4p1=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"" /> <ResourceManagerEndpoint i:nil=""true"" /> <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix> <SubscriptionId>d1e52cbc-b073-42e2-a0a0-c2f547118a6f</SubscriptionId> <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix> </AzureSubscriptionData> <AzureSubscriptionData> <ActiveDirectoryEndpoint i:nil=""true"" /> <ActiveDirectoryServiceEndpointResourceId i:nil=""true"" /> <ActiveDirectoryTenantId i:nil=""true"" /> <ActiveDirectoryUserId i:nil=""true"" /> <CloudStorageAccount i:nil=""true"" /> <GalleryEndpoint i:nil=""true"" /> <IsDefault>false</IsDefault> <LoginType i:nil=""true"" /> <ManagementCertificate>3AF24D48B97730E5C4C9CCB12397B5E046F79E09</ManagementCertificate> <ManagementEndpoint>https://management.core.chinacloudapi.cn/</ManagementEndpoint> <Name>Mooncake Test</Name> <RegisteredResourceProviders xmlns:d4p1=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"" /> <ResourceManagerEndpoint i:nil=""true"" /> <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix> <SubscriptionId>c14d7dc5-ed4d-4346-a02f-9f1bcf78fb66</SubscriptionId> <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix> </AzureSubscriptionData> </Subscriptions> </ProfileData>"; oldProfileDataBadSubscription = @"<?xml version=""1.0"" encoding=""utf-8""?> <ProfileData xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/Microsoft.Azure.Common.Extensions""> <DefaultEnvironmentName>AzureCloud</DefaultEnvironmentName> <Environments> </Environments> <Subscriptions> <AzureSubscriptionData> <ActiveDirectoryEndpoint i:nil=""true"" /> <ActiveDirectoryServiceEndpointResourceId i:nil=""true"" /> <ActiveDirectoryTenantId i:nil=""true"" /> <ActiveDirectoryUserId i:nil=""true"" /> <CloudStorageAccount i:nil=""true"" /> <GalleryEndpoint i:nil=""true"" /> <IsDefault>true</IsDefault> <LoginType i:nil=""true"" /> <ManagementCertificate i:nil=""true""/> <ManagementEndpoint>https://management.core.windows.net/</ManagementEndpoint> <Name>Test Nill ID</Name> <RegisteredResourceProviders xmlns:d4p1=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"" /> <ResourceManagerEndpoint i:nil=""true"" /> <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix> <SubscriptionId i:nil=""true"" /> <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix> </AzureSubscriptionData> <AzureSubscriptionData> <ActiveDirectoryEndpoint i:nil=""true"" /> <ActiveDirectoryServiceEndpointResourceId i:nil=""true"" /> <ActiveDirectoryTenantId i:nil=""true"" /> <ActiveDirectoryUserId>[email protected]</ActiveDirectoryUserId> <CloudStorageAccount i:nil=""true"" /> <GalleryEndpoint i:nil=""true"" /> <IsDefault>true</IsDefault> <LoginType i:nil=""true"" /> <ManagementCertificate i:nil=""true""/> <ManagementEndpoint>Bad Data</ManagementEndpoint> <Name>Test Bad Management Endpoint</Name> <RegisteredResourceProviders xmlns:d4p1=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"" /> <ResourceManagerEndpoint i:nil=""true"" /> <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix> <SubscriptionId>06E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1F</SubscriptionId> <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix> </AzureSubscriptionData> <AzureSubscriptionData> <ActiveDirectoryEndpoint i:nil=""true"" /> <ActiveDirectoryServiceEndpointResourceId i:nil=""true"" /> <ActiveDirectoryTenantId i:nil=""true"" /> <ActiveDirectoryUserId>[email protected]</ActiveDirectoryUserId> <CloudStorageAccount i:nil=""true"" /> <GalleryEndpoint i:nil=""true"" /> <IsDefault>true</IsDefault> <LoginType i:nil=""true"" /> <ManagementCertificate i:nil=""true""/> <ManagementEndpoint i:nil=""true""/> <Name>Test Null Management Endpoint</Name> <RegisteredResourceProviders xmlns:d4p1=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"" /> <ResourceManagerEndpoint i:nil=""true"" /> <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix> <SubscriptionId>06E3F6FD-A3AA-439A-8FC4-1F5C41D2ADFF</SubscriptionId> <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix> </AzureSubscriptionData> <AzureSubscriptionData> <ActiveDirectoryEndpoint>https://login.windows.net/</ActiveDirectoryEndpoint> <ActiveDirectoryServiceEndpointResourceId>https://management.core.windows.net/</ActiveDirectoryServiceEndpointResourceId> <ActiveDirectoryTenantId>72f988bf-86f1-41af-91ab-2d7cd011db47</ActiveDirectoryTenantId> <ActiveDirectoryUserId>[email protected]</ActiveDirectoryUserId> <CloudStorageAccount i:nil=""true"" /> <GalleryEndpoint i:nil=""true"" /> <IsDefault>false</IsDefault> <LoginType i:nil=""true"" /> <ManagementCertificate>3AF24D48B97730E5C4C9CCB12397B5E046F79E99</ManagementCertificate> <ManagementEndpoint>https://management.core.windows.net/</ManagementEndpoint> <Name>Test Bad Cert</Name> <RegisteredResourceProviders xmlns:d4p1=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"" /> <ResourceManagerEndpoint i:nil=""true"" /> <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix> <SubscriptionId>d1e52cbc-b073-42e2-a0a0-c2f547118a6f</SubscriptionId> <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix> </AzureSubscriptionData> </Subscriptions> </ProfileData>"; oldProfileDataCorruptedFile = @"<?xml version=""1.0"" encoding=""utf-8""?> <ProfileData xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/Microsoft.Azure.Common.Extensions""> <DefaultEnvironmentName>AzureCloud</DefaultEnvironmentName> <Environments bad> <AzureEnvironmentData> <ActiveDirectoryServiceEndpointResourceId>https://management.core.windows.net/</ActiveDirectoryServiceEndpointResourceId> <AdTenantUrl>https://login.windows-ppe.net/</AdTenantUrl> <CommonTenantId>Common</CommonTenantId> <GalleryEndpoint>https://current.gallery.azure-test.net</GalleryEndpoint> <ManagementPortalUrl>http://go.microsoft.com/fwlink/?LinkId=254433</ManagementPortalUrl> <Name>Current</Name> <PublishSettingsFileUrl>d:\Code\azure.publishsettings</PublishSettingsFileUrl> <ResourceManagerEndpoint>https://api-current.resources.windows-int.net/</ResourceManagerEndpoint> <ServiceEndpoint>https://umapi.rdfetest.dnsdemo4.com:8443/</ServiceEndpoint> <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix> <StorageEndpointSuffix i:nil=""true"" /> <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix> </AzureEnvironmentData> <Subscriptions> </Subscriptions> </ProfileData>"; jsonProfileWithoutAccount = @"{ ""Environments"": [], ""Subscriptions"": [ { ""Id"": ""7e11f45f-70e6-430a-a4fc-af338aa22c11"", ""Name"": ""Test"", ""Environment"": ""AzureCloud"", ""Account"": ""*****@*****.**"", ""Properties"": { ""SupportedModes"": ""AzureServiceManagement"", ""Default"": ""True"", ""StorageAccount"": ""rjfmmanagement"" } } ], ""Accounts"": [] }"; jsonProfileWithBadData = @"{ ""Environments"": [], ""Subscriptions"": { { ""Id"": ""7e11f45f-70e6-430a-a4fc-af338aa22c11"", ""Name"": ""Test"", ""Environment"": ""AzureCloud"", ""Account"": ""*****@*****.**"", ""Properties"": { ""SupportedModes"": ""AzureServiceManagement"", ""Default"": ""True"", ""StorageAccount"": ""rjfmmanagement"" } } ], ""Accounts"": [] }"; }