Exemplo n.º 1
0
 public static BatchManagementClient GetBatchManagementClient(RecordedDelegatingHandler handler)
 {
     handler.IsPassThrough = false;
     var client = new BatchManagementClient(new TokenCredentials("xyz"), handler);
     client.SubscriptionId = "00000000-0000-0000-0000-000000000000";
     return client;
 }
        public async Task DeleteBatchAccountAsync(Guid subscriptionId, string resourceGroupName, string batchAccountName)
        {
            var accessToken = await GetAccessToken();

            var token       = new TokenCredentials(accessToken);
            var batchClient = new BatchManagementClient(token)
            {
                SubscriptionId = subscriptionId.ToString()
            };

            try
            {
                await batchClient.BatchAccount.BeginDeleteAsync(resourceGroupName, batchAccountName);
            }
            catch (CloudException cEx)
            {
                if (cEx.Response?.StatusCode != HttpStatusCode.NotFound)
                {
                    _logger.LogError(cEx,
                                     $"Exception deleting batch account {batchAccountName} " +
                                     $"in resource group {resourceGroupName} " +
                                     $"in subscription {subscriptionId} " +
                                     $"with request {cEx.RequestId}");
                    throw;
                }
            }
        }
        public void GetDetectorValidateResponse()
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(@"{
                    'type': 'Microsoft.Batch/batchAccounts/detectors',
                    'id': '/subscriptions/subid/resourceGroups/default-azurebatch-japaneast/providers/Microsoft.Batch/batchAccounts/sampleacct/detectors/poolsAndNodes',
                    'name': 'poolsAndNodes',
                    'properties': {
                        'value': 'ew0KICAibWV0YWRhdGEiOiB7DQogICAgImlkIjogInBvb2xzQW5kTm9kZXMiLA0KICAgICJuYW1lIjogIlBvb2xzIGFuZCBOb2RlcyIsDQogICAgImRlc2NyaXB0aW9uIjogbnVsbCwNCiAgICAiYXV0aG9yIjogIiIsDQogICAgImNhdGVnb3J5IjogbnVsbCwNCiAgICAic3VwcG9ydFRvcGljTGlzdCI6IFsNCiAgICAgIHsNCiAgICAgICAgImlkIjogIjMyNjM1MDc3IiwNCiAgICAgICAgInBlc0lkIjogIjE1NjE0IiwNCiAgICAgICAgInR5cGVJZCI6ICJEaWFnbm9zdGljcy5Nb2RlbHN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xsLA0KICAgICJ0eXBlIjogIkFuYWx5c2lzIiwNCiAgICAic2NvcmUiOiAwLjANCiAgfSwNCiAgImRhdGFzZXQiOiBbXSwNCiAgInN0YXR1cyI6IHsNCiAgICAibWVzc2FnZSI6IG51bGwsDQogICAgInN0YXR1c0lkIjogNA0KICB9LA0KICAiZGF0YVByb3ZpZGVyc01ldGFkYXRhIjogbnVsbCwNCiAgInN1Z2dlc3RlZFV0dGVyYW5jZXMiOiBudWxsDQp9'
                    }
                }"
                                            )
            };

            response.Headers.Add("x-ms-request-id", "1");
            var handler = new RecordedDelegatingHandler(response)
            {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            BatchManagementClient client = BatchTestHelper.GetBatchManagementClient(handler);

            DetectorResponse result = client.BatchAccount.GetDetector("default-azurebatch-japaneast", "sampleacct", "poolsAndNodes");

            Assert.Equal(HttpMethod.Get, handler.Method);
            Assert.NotNull(handler.RequestHeaders.GetValues("User-Agent"));

            Assert.Equal("poolsAndNodes", result.Name);
            Assert.NotEmpty(result.Value);
        }
Exemplo n.º 4
0
        public async Task <List <BatchAccount> > GetBatchAccounts(string subscriptionId, string location)
        {
            var cacheKey = CacheKeys.MakeKey(CacheKeys.AccountList, subscriptionId, location);
            var cached   = HttpContext.Session.Get <List <BatchAccount> >(cacheKey);

            if (cached != null)
            {
                return(cached);
            }

            var accessToken = await GetAccessToken();

            var token       = new TokenCredentials(accessToken);
            var batchClient = new BatchManagementClient(token)
            {
                SubscriptionId = subscriptionId
            };
            var batchAccounts = await batchClient.BatchAccount.ListAsync();

            var orderedAccounts = batchAccounts
                                  .Where(acc => string.IsNullOrWhiteSpace(location) || acc.Location.Equals(location, StringComparison.OrdinalIgnoreCase))
                                  .OrderBy(acc => acc.Name.ToUpperInvariant())
                                  .ToList();

            return(HttpContext.Session.Set(cacheKey, orderedAccounts));
        }
Exemplo n.º 5
0
        public static BatchManagementClient OpenBatchManagementClient()
        {
            SubscriptionCloudCredentials subscriptionCloudCredentials;

            if (IsManagementUrlAValidProductionURL())
            {
                subscriptionCloudCredentials = GetBatchProductionTokenCloudCredentials();
            }
            else
            {
                subscriptionCloudCredentials = GetBatchTestTenantCloudCredentials();
            }

            string managementUrl = Configuration.BatchManagementUrl;

            var managementClient = new BatchManagementClient(subscriptionCloudCredentials, new Uri(managementUrl));

            //Add the extra headers as specified in the configuration
            foreach (KeyValuePair <string, string> extraHeader in Configuration.BatchTRPExtraHeaders)
            {
                managementClient.HttpClient.DefaultRequestHeaders.Add(extraHeader.Key, extraHeader.Value);
            }

            return(managementClient);
        }
Exemplo n.º 6
0
        private void SetupManagementClients(MockContext context)
        {
            ResourceManagementClient = GetResourceManagementClient(context);
            BatchManagementClient    = GetBatchManagementClient(context);

            _helper.SetupManagementClients(ResourceManagementClient, BatchManagementClient);
        }
Exemplo n.º 7
0
        public static async Task UploadTestApplicationPackageIfNotAlreadyUploadedAsync(
            string appPackageName,
            string applicationVersion,
            string accountName,
            string resourceGroupName)
        {
            using BatchManagementClient mgmtClient = IntegrationTestCommon.OpenBatchManagementClient();
            IPage <Application> applicationSummaries =
                await mgmtClient.Application.ListAsync(resourceGroupName, accountName).ConfigureAwait(false);

            bool testPackageAlreadyUploaded =
                applicationSummaries.Any(a => string.Equals(appPackageName, a.Id, StringComparison.OrdinalIgnoreCase));

            if (!testPackageAlreadyUploaded)
            {
                const string format = "zip";

                var addResponse =
                    await
                    mgmtClient.ApplicationPackage.CreateAsync(resourceGroupName, accountName, appPackageName, applicationVersion)
                    .ConfigureAwait(false);

                var storageUrl = addResponse.StorageUrl;

                await IntegrationTestCommon.UploadTestApplicationAsync(storageUrl).ConfigureAwait(false);

                await
                mgmtClient.ApplicationPackage.ActivateAsync(
                    resourceGroupName,
                    accountName,
                    appPackageName,
                    applicationVersion,
                    format).ConfigureAwait(false);
            }
        }
Exemplo n.º 8
0
        public static BatchManagementClient OpenBatchManagementClient()
        {
            ServiceClientCredentials credentials;

            if (IsManagementUrlAValidProductionURL())
            {
                string accessToken = GetAuthenticationTokenAsync("https://management.core.windows.net/").Result;
                credentials = new TokenCredentials(accessToken);
            }
            else
            {
                credentials = GetBatchTestTenantCloudCredentials();
            }

            string managementUrl = TestCommon.Configuration.BatchManagementUrl;

            var managementClient = new BatchManagementClient(credentials)
            {
                BaseUri        = new Uri(managementUrl),
                SubscriptionId = TestCommon.Configuration.BatchSubscription
            };

            //Add the extra headers as specified in the configuration
            foreach (KeyValuePair <string, string> extraHeader in TestCommon.Configuration.BatchTRPExtraHeaders)
            {
                managementClient.HttpClient.DefaultRequestHeaders.Add(extraHeader.Key, extraHeader.Value);
            }

            return(managementClient);
        }
Exemplo n.º 9
0
        public static async Task DeleteApplicationAsync(string applicationPackage, string resourceGroupName, string accountName)
        {
            using BatchManagementClient mgmtClient = IntegrationTestCommon.OpenBatchManagementClient();
            await mgmtClient.ApplicationPackage.DeleteAsync(resourceGroupName, accountName, applicationPackage, Version).ConfigureAwait(false);

            await mgmtClient.Application.DeleteAsync(resourceGroupName, accountName, applicationPackage).ConfigureAwait(false);
        }
        public async Task <Config.BatchAccount> CreateBatchAccountAsync(
            Guid subscriptionId,
            string location,
            string resourceGroupName,
            string batchAccountName,
            string storageAccountResourceId,
            string environmentName)
        {
            await RegisterProvider(subscriptionId, "Microsoft.Batch");

            var accessToken = await GetAccessToken();

            var token       = new TokenCredentials(accessToken);
            var batchClient = new BatchManagementClient(token)
            {
                SubscriptionId = subscriptionId.ToString()
            };

            var parameters = new BatchAccountCreateParameters(
                location,
                GetEnvironmentTags(environmentName),
                new AutoStorageBaseProperties(storageAccountResourceId));

            var batchAccount = await batchClient.BatchAccount.CreateAsync(resourceGroupName, batchAccountName, parameters);

            return(new Config.BatchAccount
            {
                ResourceId = batchAccount.Id,
                Location = batchAccount.Location,
                Url = $"https://{batchAccount.AccountEndpoint}",
                ExistingResource = false,
            });
        }
Exemplo n.º 11
0
        public static async Task EnableAutoStorageAsync()
        {
            using (BatchManagementClient managementClient = OpenBatchManagementClient())
            {
                //TODO: Why do we need this...?
                ServicePointManager.ServerCertificateValidationCallback =
                    delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
                {
                    HttpWebRequest request = sender as HttpWebRequest;
                    if (request != null)
                    {
                        if (request.Address.ToString().Contains(Configuration.BatchManagementUrl))
                        {
                            return(true);
                        }
                    }
                    return(sslPolicyErrors == SslPolicyErrors.None);        //use the default validation for all other certificates
                };

                //If the account doesn't already have auto storage enabled, enable it
                BatchAccountGetResponse getAccountResponse = await managementClient.Accounts.GetAsync(Configuration.BatchAccountResourceGroup, Configuration.BatchAccountName);

                if (getAccountResponse.Resource.Properties.AutoStorage == null)
                {
                    const string classicStorageAccountGroup = "Microsoft.ClassicStorage";
                    const string storageAccountGroup        = "Microsoft.Storage";
                    string       resourceFormatString       = $"/subscriptions/{Configuration.BatchSubscription}/resourceGroups/{Configuration.StorageAccountResourceGroup}/providers/" + "{0}" +
                                                              $"/storageAccounts/{Configuration.StorageAccountName}";

                    string classicStorageAccountFullResourceId = string.Format(resourceFormatString, classicStorageAccountGroup);
                    string storageAccountFullResourceId        = string.Format(resourceFormatString, storageAccountGroup);

                    var updateParameters = new BatchAccountUpdateParameters()
                    {
                        Properties = new AccountBaseProperties
                        {
                            AutoStorage = new AutoStorageBaseProperties
                            {
                                StorageAccountId = classicStorageAccountFullResourceId
                            }
                        }
                    };
                    try
                    {
                        await managementClient.Accounts.UpdateAsync(Configuration.BatchAccountResourceGroup, Configuration.BatchAccountName, updateParameters);
                    }
                    catch (Exception e) when(e.Message.Contains("The specified storage account could not be found"))
                    {
                        //If the storage account could not be found, it might be because we looked in "Classic" -- in that case swallow
                        //the exception.
                    }

                    updateParameters.Properties.AutoStorage.StorageAccountId = storageAccountFullResourceId;
                    await managementClient.Accounts.UpdateAsync(Configuration.BatchAccountResourceGroup, Configuration.BatchAccountName, updateParameters);
                }
            }
        }
Exemplo n.º 12
0
        public static BatchManagementClient GetBatchManagementClient(RecordedDelegatingHandler handler)
        {
            handler.IsPassThrough = false;
            var client = new BatchManagementClient(new TokenCredentials("xyz"), handler);

            client.SubscriptionId = "00000000-0000-0000-0000-000000000000";
            if (HttpMockServer.Mode != HttpRecorderMode.Record)
            {
                client.LongRunningOperationRetryTimeout = 0;
            }
            return(client);
        }
        public void Dispose()
        {
            BatchManagementClient mgmtClient = TestCommon.OpenBatchManagementClient();
            string accountName       = TestCommon.Configuration.BatchAccountName;
            string resourceGroupName = TestCommon.Configuration.BatchAccountResourceGroup;

            Func <Task> cleanupTask = async() =>
            {
                await mgmtClient.Applications.DeleteApplicationPackageAsync(resourceGroupName, accountName, AppPackageName, Version);

                await mgmtClient.Applications.DeleteApplicationAsync(resourceGroupName, accountName, AppPackageName);
            };

            Task.Run(cleanupTask).GetAwaiter().GetResult();
        }
Exemplo n.º 14
0
        private static async Task UploadTestApplicationAndActivateAsync(string appPackageName, string applicationVersion, string resourceGroupName, string accountName)
        {
            const string format = "zip";

            using (BatchManagementClient mgmtClient = IntegrationTestCommon.OpenBatchManagementClient())
            {
                var addResponse = await mgmtClient.ApplicationPackage.CreateAsync(resourceGroupName, accountName, appPackageName, applicationVersion).ConfigureAwait(false);

                var storageUrl = addResponse.StorageUrl;

                await IntegrationTestCommon.UploadTestApplicationAsync(storageUrl).ConfigureAwait(false);

                await mgmtClient.ApplicationPackage.ActivateAsync(resourceGroupName, accountName, appPackageName, applicationVersion, format).ConfigureAwait(false);
            }
        }
Exemplo n.º 15
0
        public static async Task DeleteApplicationAsync(string applicationPackage, string resourceGroupName, string accountName)
        {
            using (BatchManagementClient mgmtClient = TestCommon.OpenBatchManagementClient())
            {
                var deleteApplicationPackage =
                    await
                    mgmtClient.Applications.DeleteApplicationPackageAsync(resourceGroupName, accountName, applicationPackage, Version).ConfigureAwait(false);

                Assert.Equal(deleteApplicationPackage.StatusCode, HttpStatusCode.NoContent);

                var deleteApplicationResponse =
                    await mgmtClient.Applications.DeleteApplicationAsync(resourceGroupName, accountName, applicationPackage).ConfigureAwait(false);

                Assert.Equal(deleteApplicationResponse.StatusCode, HttpStatusCode.NoContent);
            }
        }
        public async Task <List <BatchAccount> > GetBatchAccounts(string subscriptionId, string location)
        {
            var accessToken = await GetAccessToken();

            var token       = new TokenCredentials(accessToken);
            var batchClient = new BatchManagementClient(token)
            {
                SubscriptionId = subscriptionId
            };
            var batchAccounts = await batchClient.BatchAccount.ListAsync();

            return(batchAccounts
                   .Where(acc => string.IsNullOrWhiteSpace(location) || acc.Location.Equals(location, StringComparison.OrdinalIgnoreCase))
                   .OrderBy(acc => acc.Name.ToUpperInvariant())
                   .ToList());
        }
Exemplo n.º 17
0
        public static async Task UploadTestApplicationPackageIfNotAlreadyUploadedAsync(string appPackageName, string applicationVersion)
        {
            string accountName       = TestCommon.Configuration.BatchAccountName;
            string resourceGroupName = TestCommon.Configuration.BatchAccountResourceGroup;

            using (BatchManagementClient mgmtClient = IntegrationTestCommon.OpenBatchManagementClient())
            {
                var applicationSummaries = await mgmtClient.Application.ListAsync(resourceGroupName, accountName);

                bool testPackageAlreadyUploaded = applicationSummaries.Any(a =>
                                                                           string.Equals(appPackageName, a.Id, StringComparison.OrdinalIgnoreCase) &&
                                                                           string.Equals(applicationVersion, a.DefaultVersion, StringComparison.OrdinalIgnoreCase));

                if (!testPackageAlreadyUploaded)
                {
                    await UploadTestApplicationAndActivateAsync(appPackageName, applicationVersion, resourceGroupName, accountName).ConfigureAwait(false);
                }
            }
        }
Exemplo n.º 18
0
        static void Main(string[] args)
        {
            Console.WriteLine("Logging in to Azure...");
            AzureCredentials credentials = SdkContext.AzureCredentialsFactory
                                           .FromServicePrincipal(clientId, clientSecret, azureTenantId, AzureEnvironment.AzureGlobalCloud);
            var azure = Azure
                        .Configure()
                        .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                        .Authenticate(credentials)
                        .WithSubscription(azureSubscriptionId);

            Console.WriteLine("Successfully logged in to Azure");

            //Create resource group
            Console.WriteLine("Creating resource group...");
            var resourceGroup = azure.ResourceGroups
                                .Define("DemoGroup")
                                .WithRegion(Region.AsiaSouthEast)
                                .Create();

            Console.WriteLine($"Resource group '{resourceGroup.Name}' created");

            //
            BatchManagementClient batchManagementClient = new BatchManagementClient(credentials);
            // Create a new Batch account
            var batchAccCreateParameters = new BatchAccountCreateParameters()
            {
                Location = "West US"
            };

            batchManagementClient.BatchAccount.CreateAsync("DemoGroup", "sonubathaccount1", batchAccCreateParameters).GetAwaiter().GetResult();

            // Get the new account from the Batch service
            BatchAccount account = batchManagementClient.BatchAccount.GetAsync("DemoGroup", "sonubathaccount1").GetAwaiter().GetResult();


            // Delete the account
            batchManagementClient.BatchAccount.DeleteAsync("DemoGroup", account.Name);
        }
Exemplo n.º 19
0
        public async Task DeleteBatchAccountAsync(Guid subscriptionId, string resourceGroupName, string batchAccountName)
        {
            var accessToken = await GetAccessToken();

            var token       = new TokenCredentials(accessToken);
            var batchClient = new BatchManagementClient(token)
            {
                SubscriptionId = subscriptionId.ToString()
            };

            try
            {
                await batchClient.BatchAccount.BeginDeleteAsync(resourceGroupName, batchAccountName);
            }
            catch (CloudException cEx)
            {
                if (cEx.Response?.StatusCode != HttpStatusCode.NotFound)
                {
                    throw;
                }
            }
        }
Exemplo n.º 20
0
        public static async Task UploadTestApplicationPackageIfNotAlreadyUploadedAsync(
            string appPackageName,
            string applicationVersion,
            string accountName,
            string resourceGroupName)
        {
            using (BatchManagementClient mgmtClient = TestCommon.OpenBatchManagementClient())
            {
                ListApplicationsResponse applicationSummaries =
                    await mgmtClient.Applications.ListAsync(resourceGroupName, accountName, new ListApplicationsParameters()).ConfigureAwait(false);

                bool testPackageAlreadyUploaded =
                    applicationSummaries.Applications.Any(a => string.Equals(appPackageName, a.Id, StringComparison.OrdinalIgnoreCase));

                if (!testPackageAlreadyUploaded)
                {
                    const string format = "zip";

                    var addResponse =
                        await
                        mgmtClient.Applications.AddApplicationPackageAsync(resourceGroupName, accountName, appPackageName, applicationVersion)
                        .ConfigureAwait(false);

                    var storageUrl = addResponse.StorageUrl;

                    await TestCommon.UploadTestApplicationAsync(storageUrl).ConfigureAwait(false);

                    await
                    mgmtClient.Applications.ActivateApplicationPackageAsync(
                        resourceGroupName,
                        accountName,
                        appPackageName,
                        applicationVersion,
                        new ActivateApplicationPackageParameters { Format = format }).ConfigureAwait(false);
                }
            }
        }
        public async Task UploadCertificateToBatchAccountAsync(
            Guid subscriptionId,
            Config.BatchAccount batchAccount,
            X509Certificate2 certificate,
            string password)
        {
            var accessToken = await GetAccessToken();

            var token       = new TokenCredentials(accessToken);
            var batchClient = new BatchManagementClient(token, _httpClientFactory.CreateClient(), false)
            {
                SubscriptionId = subscriptionId.ToString()
            };

            // Check if the cert has already been uploaded.
            var existingCerts = await batchClient.Certificate.ListByBatchAccountAsync(batchAccount.ResourceGroupName, batchAccount.Name);

            if (existingCerts != null &&
                existingCerts.Any(c =>
                                  c.Thumbprint.Equals(certificate.Thumbprint, StringComparison.InvariantCultureIgnoreCase)))
            {
                return;
            }

            var parameters = new CertificateCreateOrUpdateParameters(
                Convert.ToBase64String(certificate.Export(X509ContentType.Pkcs12, password)),
                thumbprint: certificate.Thumbprint,
                thumbprintAlgorithm: "SHA1",
                password: password);

            await batchClient.Certificate.CreateAsync(
                batchAccount.ResourceGroupName,
                batchAccount.Name,
                $"SHA1-{certificate.Thumbprint}",
                parameters);
        }
Exemplo n.º 22
0
        public static async Task UpdateApplicationPackageAsync(string applicationId, string defaultVersion, string displayName, bool hasDefaultVersion)
        {
            string accountName       = TestCommon.Configuration.BatchAccountName;
            string resourceGroupName = TestCommon.Configuration.BatchAccountResourceGroup;

            BatchManagementClient mgmtClient = IntegrationTestCommon.OpenBatchManagementClient();

            if (hasDefaultVersion)
            {
                await mgmtClient.Application.UpdateAsync(
                    resourceGroupName,
                    accountName,
                    applicationId,
                    new UpdateApplicationParameters { AllowUpdates = true, DefaultVersion = defaultVersion, DisplayName = displayName });
            }
            else
            {
                await mgmtClient.Application.UpdateAsync(
                    resourceGroupName,
                    accountName,
                    applicationId,
                    new UpdateApplicationParameters { AllowUpdates = true, DisplayName = displayName });
            }
        }
Exemplo n.º 23
0
        private async Task <bool> CreateBatchPool(CommandLineArgs cmdLine, string poolId)
        {
            var batchAccountName = cmdLine.ConnectionArgs.BatchAccountName;
            var batchAccountKey  = cmdLine.ConnectionArgs.BatchAccountKey.EncodeBase64();
            var batchUrl         = cmdLine.ConnectionArgs.BatchAccountUrl;

            var nodeCount = cmdLine.BatchArgs.BatchNodeCount;
            var vmSize    = cmdLine.BatchArgs.BatchVmSize;
            var os        = cmdLine.BatchArgs.BatchPoolOs;

            var userAssignedResourceId = cmdLine.IdentityArgs.ResourceId;
            var userAssignedPrinId     = cmdLine.IdentityArgs.PrincipalId;
            var userAssignedClientId   = cmdLine.IdentityArgs.ClientId;
            var resourceGroupName      = cmdLine.IdentityArgs.ResourceGroup;
            var subscriptionId         = cmdLine.IdentityArgs.SubscriptionId;


            log.LogInformation($"Creating pool [{poolId}]...");

            //var creds = new BatchSharedKeyCredential(batchAccountName, batchAccountKey);
            if (cmdLine.IdentityArgs != null)
            {
                AadHelper.ManagedIdentityClientId = cmdLine.IdentityArgs.ClientId;
            }
            var creds            = new CustomClientCredentials(AadHelper.TokenCredential);
            var managementClient = new BatchManagementClient(creds);

            managementClient.SubscriptionId = subscriptionId;

            //// From: https://docs.microsoft.com/en-us/azure/batch/managed-identity-pools
            bm.ImageReference imageReference;
            bm.VirtualMachineConfiguration virtualMachineConfiguration;
            switch (os)
            {
            case OsType.Linux:
                imageReference = new bm.ImageReference(publisher: "Canonical", offer: "UbuntuServer", sku: "18.04-lts", version: "latest");
                virtualMachineConfiguration = new bm.VirtualMachineConfiguration(imageReference: imageReference, nodeAgentSkuId: "batch.node.ubuntu 18.04");
                break;

            case OsType.Windows:
            default:
                imageReference = new bm.ImageReference(publisher: "MicrosoftWindowsServer", offer: "WindowsServer", sku: "2016-Datacenter-with-containers", version: "latest");
                virtualMachineConfiguration = new bm.VirtualMachineConfiguration(imageReference: imageReference, nodeAgentSkuId: "batch.node.windows amd64");

                break;
            }

            var deploymentConfig = new bm.DeploymentConfiguration()
            {
                VirtualMachineConfiguration = virtualMachineConfiguration
            };
            var ids = new Dictionary <string, bm.UserAssignedIdentities>();

            ids.Add(userAssignedResourceId, new bm.UserAssignedIdentities(principalId: userAssignedPrinId, clientId: userAssignedClientId));

            var poolIdentity = new bm.BatchPoolIdentity()
            {
                Type = bm.PoolIdentityType.UserAssigned, UserAssignedIdentities = ids
            };
            var scaleSettings = new bm.ScaleSettings()
            {
                FixedScale = new bm.FixedScaleSettings()
                {
                    TargetDedicatedNodes = nodeCount
                }
            };

            var poolParameters = new bm.Pool(name: poolId)
            {
                VmSize                  = vmSize,
                ScaleSettings           = scaleSettings,
                DeploymentConfiguration = deploymentConfig,
                Identity                = poolIdentity
            };

            try
            {
                var pool = await managementClient.Pool.CreateWithHttpMessagesAsync(
                    poolName : poolId,
                    resourceGroupName : resourceGroupName,
                    accountName : batchAccountName,
                    parameters : poolParameters,
                    cancellationToken : default(CancellationToken));

                if (!pool.Response.IsSuccessStatusCode)
                {
                    log.LogWarning($"Issue creating pool: {pool.Body.ProvisioningState.ToString()}");
                    return(false);
                }
            }
            catch (Exception exe)
            {
                log.LogError($"Error creating Batch Pool: {exe.ToString()}");
                return(false);
            }
            return(true);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Performs various Batch account operations using the Batch Management library.
        /// </summary>
        /// <param name="accessToken">The access token to use for authentication.</param>
        /// <param name="subscriptionId">The subscription id to use for creating the Batch management client</param>
        /// <param name="location">The location where the Batch account will be created.</param>
        /// <returns>A <see cref="System.Threading.Tasks.Task"/> object that represents the asynchronous operation.</returns>
        private static async Task PerformBatchAccountOperationsAsync(string accessToken, string subscriptionId, string location)
        {
            using (BatchManagementClient batchManagementClient = new BatchManagementClient(new TokenCredentials(accessToken)))
            {
                batchManagementClient.SubscriptionId = subscriptionId;

                // Get the account quota for the subscription
                BatchLocationQuota quotaResponse = await batchManagementClient.Location.GetQuotasAsync(location);

                Console.WriteLine("Your subscription can create {0} account(s) in the {1} region.", quotaResponse.AccountQuota, location);
                Console.WriteLine();

                // Create account
                string accountName = PromptUserForAccountName();
                Console.WriteLine("Creating account {0}...", accountName);
                await batchManagementClient.BatchAccount.CreateAsync(ResourceGroupName, accountName, new BatchAccountCreateParameters()
                {
                    Location = location
                });

                Console.WriteLine("Account {0} created", accountName);
                Console.WriteLine();

                // Get account
                Console.WriteLine("Getting account {0}...", accountName);
                BatchAccount account = await batchManagementClient.BatchAccount.GetAsync(ResourceGroupName, accountName);

                Console.WriteLine("Got account {0}:", account.Name);
                Console.WriteLine("  Account location: {0}", account.Location);
                Console.WriteLine("  Account resource type: {0}", account.Type);
                Console.WriteLine("  Account id: {0}", account.Id);
                Console.WriteLine();

                // Print account quotas
                Console.WriteLine("Quotas for account {0}:", account.Name);
                Console.WriteLine("  Dedicated core quota: {0}", account.DedicatedCoreQuota);
                Console.WriteLine("  Low priority core quota: {0}", account.LowPriorityCoreQuota);
                Console.WriteLine("  Pool quota: {0}", account.PoolQuota);
                Console.WriteLine("  Active job and job schedule quota: {0}", account.ActiveJobAndJobScheduleQuota);
                Console.WriteLine();

                // Get account keys
                Console.WriteLine("Getting account keys of account {0}...", account.Name);
                BatchAccountKeys accountKeys = await batchManagementClient.BatchAccount.GetKeysAsync(ResourceGroupName, account.Name);

                Console.WriteLine("  Primary key of account {0}:   {1}", account.Name, accountKeys.Primary);
                Console.WriteLine("  Secondary key of account {0}: {1}", account.Name, accountKeys.Secondary);
                Console.WriteLine();

                // Regenerate primary account key
                Console.WriteLine("Regenerating the primary key of account {0}...", account.Name);
                BatchAccountKeys newKeys = await batchManagementClient.BatchAccount.RegenerateKeyAsync(
                    ResourceGroupName, account.Name,
                    AccountKeyType.Primary);

                Console.WriteLine("  New primary key of account {0}: {1}", account.Name, newKeys.Primary);
                Console.WriteLine("  Secondary key of account {0}:   {1}", account.Name, newKeys.Secondary);
                Console.WriteLine();

                // List total number of accounts under the subscription id
                IPage <BatchAccount> listResponse = await batchManagementClient.BatchAccount.ListAsync();

                var accounts = new List <BatchAccount>();
                accounts.AddRange(listResponse);

                var nextLink = listResponse.NextPageLink;
                while (nextLink != null)
                {
                    listResponse = await batchManagementClient.BatchAccount.ListNextAsync(nextLink);

                    accounts.AddRange(listResponse);
                    nextLink = listResponse.NextPageLink;
                }

                Console.WriteLine("Total number of Batch accounts under subscription id {0}:  {1}", batchManagementClient.SubscriptionId, accounts.Count());

                // Determine how many additional accounts can be created in the target region
                int numAccountsInRegion = accounts.Count(o => o.Location == account.Location);
                Console.WriteLine("Accounts in {0}: {1}", account.Location, numAccountsInRegion);
                Console.WriteLine("You can create {0} more accounts in the {1} region.", quotaResponse.AccountQuota - numAccountsInRegion, account.Location);
                Console.WriteLine();

                // List accounts in the subscription
                Console.WriteLine("Listing all Batch accounts under subscription id {0}...", batchManagementClient.SubscriptionId);
                foreach (BatchAccount acct in accounts)
                {
                    Console.WriteLine("  {0} - {1} | Location: {2}", accounts.IndexOf(acct) + 1, acct.Name, acct.Location);
                }
                Console.WriteLine();

                // Delete account
                Console.Write("Hit ENTER to delete account {0}: ", account.Name);
                Console.ReadLine();
                Console.WriteLine("Deleting account {0}...", account.Name);

                try
                {
                    await batchManagementClient.BatchAccount.DeleteAsync(ResourceGroupName, account.Name);
                }
                catch (CloudException ex)
                {
                    /*  Account deletion is a long running operation. This .DeleteAsync() method will submit the account deletion request and
                     *  poll for the status of the long running operation until the account is deleted. Currently, querying for the operation
                     *  status after the account is deleted will return a 404 error, so we have to add this catch statement. This behavior will
                     *  be fixed in a future service release.
                     */
                    if (ex.Response.StatusCode != HttpStatusCode.NotFound)
                    {
                        throw;
                    }
                }

                Console.WriteLine("Account {0} deleted", account.Name);
                Console.WriteLine();
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Performs various Batch account operations using the Batch Management library.
        /// </summary>
        /// <param name="creds">The <see cref="Microsoft.Azure.TokenCloudCredentials"/> containing information about the user's
        /// Azure account and subscription.</param>
        /// <param name="location">The location where the Batch account will be created.</param>
        /// <returns>A <see cref="System.Threading.Tasks.Task"/> object that represents the asynchronous operation.</returns>
        private static async Task PerformBatchAccountOperationsAsync(TokenCloudCredentials creds, string location)
        {
            using (BatchManagementClient batchManagementClient = new BatchManagementClient(creds))
            {
                // Get the account quota for the subscription
                SubscriptionQuotasGetResponse quotaResponse = await batchManagementClient.Subscriptions.GetSubscriptionQuotasAsync(location);

                Console.WriteLine("Your subscription can create {0} account(s) in the {1} region.", quotaResponse.AccountQuota, location);
                Console.WriteLine();

                // Create account
                string accountName = PromptUserForAccountName();
                Console.WriteLine("Creating account {0}...", accountName);
                await batchManagementClient.Accounts.CreateAsync(ResourceGroupName, accountName, new BatchAccountCreateParameters()
                {
                    Location = location
                });

                Console.WriteLine("Account {0} created", accountName);
                Console.WriteLine();

                // Get account
                Console.WriteLine("Getting account {0}...", accountName);
                BatchAccountGetResponse getResponse = await batchManagementClient.Accounts.GetAsync(ResourceGroupName, accountName);

                AccountResource account = getResponse.Resource;
                Console.WriteLine("Got account {0}:", account.Name);
                Console.WriteLine("  Account location: {0}", account.Location);
                Console.WriteLine("  Account resource type: {0}", account.Type);
                Console.WriteLine("  Account id: {0}", account.Id);
                Console.WriteLine();

                // Print account quotas
                Console.WriteLine("Quotas for account {0}:", account.Name);
                Console.WriteLine("  Core quota: {0}", account.Properties.CoreQuota);
                Console.WriteLine("  Pool quota: {0}", account.Properties.PoolQuota);
                Console.WriteLine("  Active job and job schedule quota: {0}", account.Properties.ActiveJobAndJobScheduleQuota);
                Console.WriteLine();

                // Get account keys
                Console.WriteLine("Getting account keys of account {0}...", account.Name);
                BatchAccountListKeyResponse accountKeys = await batchManagementClient.Accounts.ListKeysAsync(ResourceGroupName, account.Name);

                Console.WriteLine("  Primary key of account {0}:   {1}", account.Name, accountKeys.PrimaryKey);
                Console.WriteLine("  Secondary key of account {0}: {1}", account.Name, accountKeys.SecondaryKey);
                Console.WriteLine();

                // Regenerate primary account key
                Console.WriteLine("Regenerating the primary key of account {0}...", account.Name);
                BatchAccountRegenerateKeyResponse newKeys = await batchManagementClient.Accounts.RegenerateKeyAsync(
                    ResourceGroupName, account.Name,
                    new BatchAccountRegenerateKeyParameters()
                {
                    KeyName = AccountKeyType.Primary
                });

                Console.WriteLine("  New primary key of account {0}: {1}", account.Name, newKeys.PrimaryKey);
                Console.WriteLine("  Secondary key of account {0}:   {1}", account.Name, newKeys.SecondaryKey);
                Console.WriteLine();

                // Print subscription quota information
                BatchAccountListResponse listResponse = await batchManagementClient.Accounts.ListAsync(new AccountListParameters());

                IList <AccountResource> accounts = listResponse.Accounts;
                Console.WriteLine("Total number of Batch accounts under subscription id {0}:  {1}", creds.SubscriptionId, accounts.Count);

                // Determine how many additional accounts can be created in the target region
                int numAccountsInRegion = accounts.Count(o => o.Location == account.Location);
                Console.WriteLine("Accounts in {0}: {1}", account.Location, numAccountsInRegion);
                Console.WriteLine("You can create {0} more accounts in the {1} region.", quotaResponse.AccountQuota - numAccountsInRegion, account.Location);
                Console.WriteLine();

                // List accounts in the subscription
                Console.WriteLine("Listing all Batch accounts under subscription id {0}...", creds.SubscriptionId);
                foreach (AccountResource acct in accounts)
                {
                    Console.WriteLine("  {0} - {1} | Location: {2}", accounts.IndexOf(acct) + 1, acct.Name, acct.Location);
                }
                Console.WriteLine();

                // Delete account
                Console.Write("Hit ENTER to delete account {0}: ", account.Name);
                Console.ReadLine();
                Console.WriteLine("Deleting account {0}...", account.Name);
                await batchManagementClient.Accounts.DeleteAsync(ResourceGroupName, account.Name);

                Console.WriteLine("Account {0} deleted", account.Name);
                Console.WriteLine();
            }
        }