Exemplo n.º 1
0
        ///GENMHASH:0202A00A1DCF248D2647DBDBEF2CA865:8F640179247B56242D756EB9A20DC705
        public async override Task <IBatchAccount> CreateResourceAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            HandleStorageSettings();
            var batchAccountCreateParameters = new BatchAccountCreateParameters();

            if (autoStorage != null)
            {
                batchAccountCreateParameters.AutoStorage = new AutoStorageBaseProperties
                {
                    StorageAccountId = autoStorage.StorageAccountId
                };
            }
            else
            {
                batchAccountCreateParameters.AutoStorage = null;
            }

            batchAccountCreateParameters.Location = Inner.Location;
            batchAccountCreateParameters.Tags     = Inner.Tags;

            var batchAccountInner = await Manager.Inner.BatchAccount.CreateAsync(
                ResourceGroupName,
                Name,
                batchAccountCreateParameters,
                cancellationToken);

            creatableStorageAccountKey = null;
            SetInner(batchAccountInner);
            await applicationsImpl.CommitAndGetAllAsync(cancellationToken);

            await poolsImpl.CommitAndGetAllAsync(cancellationToken);

            return(this);
        }
        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.º 3
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.º 4
0
 /// <summary>
 /// Creates a new Batch account
 /// </summary>
 /// <param name="resourceGroupName">The name of the resource group in which to create the account</param>
 /// <param name="accountName">The account name</param>
 /// <param name="parameters">Additional parameters that are associated with the creation of the account</param>
 /// <returns>The status of create operation</returns>
 public BatchAccountCreateResponse CreateAccount(string resourceGroupName, string accountName, BatchAccountCreateParameters parameters)
 {
     return(BatchManagementClient.Accounts.Create(resourceGroupName, accountName, parameters));
 }
        public async Task BatchCertificateEndToEndAsync()
        {
            using (MockContext context = StartMockContextAndInitializeClients(this.GetType().FullName))
            {
                string resourceGroupName = TestUtilities.GenerateName();
                string batchAccountName  = TestUtilities.GenerateName();
                string batchCertName     = "SHA1-cff2ab63c8c955aaf71989efa641b906558d9fb7";

                ResourceGroup group = new ResourceGroup(this.Location);
                await this.ResourceManagementClient.ResourceGroups.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, group);

                // Create an account
                BatchAccountCreateParameters createParams = new BatchAccountCreateParameters(this.Location);
                await this.BatchManagementClient.BatchAccount.CreateAsync(resourceGroupName, batchAccountName, createParams);

                try
                {
                    // Create a certificate
                    CertificateCreateOrUpdateParameters param = new CertificateCreateOrUpdateParameters("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");
                    param.Format              = CertificateFormat.Pfx;
                    param.Password            = "******";
                    param.Thumbprint          = "cff2ab63c8c955aaf71989efa641b906558d9fb7";
                    param.ThumbprintAlgorithm = "sha1";

                    var certResponse = await this.BatchManagementClient.Certificate.CreateAsync(resourceGroupName, batchAccountName, batchCertName, param);

                    Assert.Equal("CFF2AB63C8C955AAF71989EFA641B906558D9FB7", certResponse.Thumbprint);
                    var referenceId =
                        $"/subscriptions/{this.BatchManagementClient.SubscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{batchAccountName}/certificates/{batchCertName.ToUpperInvariant()}";
                    Assert.Equal(referenceId, certResponse.Id);
                    Assert.Equal(CertificateProvisioningState.Succeeded, certResponse.ProvisioningState);
                    Assert.Equal("SHA1", certResponse.ThumbprintAlgorithm);
                    Assert.Equal(CertificateFormat.Pfx, certResponse.Format);

                    // List the certificates
                    var certs = await this.BatchManagementClient.Certificate.ListByBatchAccountAsync(resourceGroupName, batchAccountName);

                    Assert.Single(certs);

                    // Get the cert
                    var cert = await this.BatchManagementClient.Certificate.GetAsync(resourceGroupName, batchAccountName, batchCertName);

                    Assert.Equal("CFF2AB63C8C955AAF71989EFA641B906558D9FB7", cert.Thumbprint);
                    Assert.Equal(referenceId, cert.Id);
                    Assert.Equal(CertificateProvisioningState.Succeeded, cert.ProvisioningState);
                    Assert.Equal("SHA1", cert.ThumbprintAlgorithm);
                    Assert.Equal(CertificateFormat.Pfx, cert.Format);
                    Assert.Null(cert.DeleteCertificateError);

                    // Update the cert
                    param          = new CertificateCreateOrUpdateParameters("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");
                    param.Password = "******";
                    certResponse   = await this.BatchManagementClient.Certificate.UpdateAsync(resourceGroupName, batchAccountName, batchCertName, param);

                    Assert.Equal(referenceId, certResponse.Id);

                    // Cancel the deletetion
                    await this.BatchManagementClient.Certificate.CancelDeletionAsync(resourceGroupName, batchAccountName, batchCertName);

                    // Delete the certificate
                    try
                    {
                        await this.BatchManagementClient.Certificate.DeleteAsync(resourceGroupName, batchAccountName, batchCertName);
                    }
                    catch (CloudException ex)
                    {
                        if (ex.Response.StatusCode != HttpStatusCode.NotFound)
                        {
                            throw;
                        }
                    }

                    // Verify certificate was deleted. A GET operation will return a 404 error and result in an exception
                    try
                    {
                        await this.BatchManagementClient.Certificate.GetAsync(resourceGroupName, batchAccountName, batchCertName);
                    }
                    catch (CloudException ex)
                    {
                        Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode);
                    }
                }
                finally
                {
                    // Clean up
                    await this.BatchManagementClient.BatchAccount.DeleteAsync(resourceGroupName, batchAccountName);

                    await this.ResourceManagementClient.ResourceGroups.DeleteWithHttpMessagesAsync(resourceGroupName);
                }
            }
        }
 /// <summary>
 /// Creates a new Batch account with the specified parameters. Existing
 /// accounts cannot be updated with this API and should instead be updated with
 /// the Update Batch Account API.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group that contains the Batch account.
 /// </param>
 /// <param name='accountName'>
 /// A name for the Batch account which must be unique within the region. Batch
 /// account names must be between 3 and 24 characters in length and must use
 /// only numbers and lowercase letters. This name is used as part of the DNS
 /// name that is used to access the Batch service in the region in which the
 /// account is created. For example:
 /// http://accountname.region.batch.azure.com/.
 /// </param>
 /// <param name='parameters'>
 /// Additional parameters for account creation.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <BatchAccount> CreateAsync(this IBatchAccountOperations operations, string resourceGroupName, string accountName, BatchAccountCreateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, accountName, parameters, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
 /// <summary>
 /// Creates a new Batch account with the specified parameters. Existing
 /// accounts cannot be updated with this API and should instead be updated with
 /// the Update Batch Account API.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group that contains the Batch account.
 /// </param>
 /// <param name='accountName'>
 /// A name for the Batch account which must be unique within the region. Batch
 /// account names must be between 3 and 24 characters in length and must use
 /// only numbers and lowercase letters. This name is used as part of the DNS
 /// name that is used to access the Batch service in the region in which the
 /// account is created. For example:
 /// http://accountname.region.batch.azure.com/.
 /// </param>
 /// <param name='parameters'>
 /// Additional parameters for account creation.
 /// </param>
 public static BatchAccount Create(this IBatchAccountOperations operations, string resourceGroupName, string accountName, BatchAccountCreateParameters parameters)
 {
     return(operations.CreateAsync(resourceGroupName, accountName, parameters).GetAwaiter().GetResult());
 }
Exemplo n.º 8
0
        /// <summary>
        /// Creates a new Batch account with the specified parameters. Existing
        /// accounts cannot be updated with this API and should instead be updated with
        /// the Update Batch Account API.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group that contains the Batch account.
        /// </param>
        /// <param name='accountName'>
        /// A name for the Batch account which must be unique within the region. Batch
        /// account names must be between 3 and 24 characters in length and must use
        /// only numbers and lowercase letters. This name is used as part of the DNS
        /// name that is used to access the Batch service in the region in which the
        /// account is created. For example:
        /// http://accountname.region.batch.azure.com/.
        /// </param>
        /// <param name='parameters'>
        /// Additional parameters for account creation.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        public async Task <AzureOperationResponse <BatchAccount, RetryHeader> > CreateWithHttpMessagesAsync(string resourceGroupName, string accountName, BatchAccountCreateParameters parameters, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Send Request
            AzureOperationResponse <BatchAccount, RetryHeader> _response = await BeginCreateWithHttpMessagesAsync(resourceGroupName, accountName, parameters, customHeaders, cancellationToken).ConfigureAwait(false);

            return(await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false));
        }
Exemplo n.º 9
0
        /// <summary>
        /// Creates a new Batch account with the specified parameters. Existing
        /// accounts cannot be updated with this API and should instead be updated with
        /// the Update Batch Account API.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group that contains the Batch account.
        /// </param>
        /// <param name='accountName'>
        /// A name for the Batch account which must be unique within the region. Batch
        /// account names must be between 3 and 24 characters in length and must use
        /// only numbers and lowercase letters. This name is used as part of the DNS
        /// name that is used to access the Batch service in the region in which the
        /// account is created. For example:
        /// http://accountname.region.batch.azure.com/.
        /// </param>
        /// <param name='parameters'>
        /// Additional parameters for account creation.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="HttpOperationException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <AzureOperationResponse <BatchAccount, RetryHeader> > BeginCreateWithHttpMessagesAsync(string resourceGroupName, string accountName, BatchAccountCreateParameters parameters, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (resourceGroupName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
            }
            if (resourceGroupName != null)
            {
                if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$"))
                {
                    throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$");
                }
            }
            if (accountName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
            }
            if (accountName != null)
            {
                if (accountName.Length > 24)
                {
                    throw new ValidationException(ValidationRules.MaxLength, "accountName", 24);
                }
                if (accountName.Length < 3)
                {
                    throw new ValidationException(ValidationRules.MinLength, "accountName", 3);
                }
                if (!System.Text.RegularExpressions.Regex.IsMatch(accountName, "^[-\\w\\._]+$"))
                {
                    throw new ValidationException(ValidationRules.Pattern, "accountName", "^[-\\w\\._]+$");
                }
            }
            if (parameters == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
            }
            if (parameters != null)
            {
                parameters.Validate();
            }
            if (Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }
            if (Client.SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("accountName", accountName);
                tracingParameters.Add("parameters", parameters);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "BeginCreate", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}").ToString();

            _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
            _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
            List <string> _queryParameters = new List <string>();

            if (Client.ApiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("PUT");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
            }


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            if (parameters != null)
            {
                _requestContent      = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200 && (int)_statusCode != 202)
            {
                var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    object _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <object>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse <BatchAccount, RetryHeader>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <BatchAccount>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            try
            {
                _result.Headers = _httpResponse.GetHeadersAsJson().ToObject <RetryHeader>(JsonSerializer.Create(Client.DeserializationSettings));
            }
            catch (JsonException ex)
            {
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
        public async Task BatchAccountEndToEndAsync()
        {
            using (MockContext context = StartMockContextAndInitializeClients(this.GetType().FullName))
            {
                string        resourceGroupName = TestUtilities.GenerateName();
                string        batchAccountName  = TestUtilities.GenerateName();
                ResourceGroup group             = new ResourceGroup(this.Location);
                await this.ResourceManagementClient.ResourceGroups.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, group);

                try
                {
                    // Check if the account exists
                    var checkAvailabilityResult = await this.BatchManagementClient.Location.CheckNameAvailabilityAsync(this.Location, batchAccountName);

                    Assert.True(checkAvailabilityResult.NameAvailable);

                    // Create an account
                    BatchAccountCreateParameters createParams = new BatchAccountCreateParameters(this.Location);
                    await this.BatchManagementClient.BatchAccount.CreateAsync(resourceGroupName, batchAccountName, createParams);

                    // Check if the account exists now
                    checkAvailabilityResult = await this.BatchManagementClient.Location.CheckNameAvailabilityAsync(this.Location, batchAccountName);

                    Assert.False(checkAvailabilityResult.NameAvailable);
                    Assert.NotNull(checkAvailabilityResult.Message);
                    Assert.NotNull(checkAvailabilityResult.Reason);

                    // Get the account and verify some properties
                    BatchAccount batchAccount = await this.BatchManagementClient.BatchAccount.GetAsync(resourceGroupName, batchAccountName);

                    Assert.Equal(batchAccountName, batchAccount.Name);
                    Assert.True(batchAccount.DedicatedCoreQuota > 0);
                    Assert.True(batchAccount.LowPriorityCoreQuota > 0);

                    // Rotate a key
                    BatchAccountKeys originalKeys = await this.BatchManagementClient.BatchAccount.GetKeysAsync(resourceGroupName, batchAccountName);

                    BatchAccountKeys newKeys = await this.BatchManagementClient.BatchAccount.RegenerateKeyAsync(resourceGroupName, batchAccountName, AccountKeyType.Primary);

                    Assert.NotEqual(originalKeys.Primary, newKeys.Primary);
                    Assert.Equal(originalKeys.Secondary, newKeys.Secondary);

                    // List accounts under the resource group
                    IPage <BatchAccount> listResponse = await this.BatchManagementClient.BatchAccount.ListByResourceGroupAsync(resourceGroupName);

                    List <BatchAccount> accounts = new List <BatchAccount>(listResponse);
                    string nextLink = listResponse.NextPageLink;
                    while (nextLink != null)
                    {
                        listResponse = await this.BatchManagementClient.BatchAccount.ListByResourceGroupNextAsync(nextLink);

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

                    Assert.Single(accounts);
                    Assert.Equal(batchAccountName, accounts.First().Name);

                    // Delete the account
                    try
                    {
                        await this.BatchManagementClient.BatchAccount.DeleteAsync(resourceGroupName, batchAccountName);
                    }
                    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;
                        }
                    }
                    // Verify account was deleted. A GET operation will return a 404 error and result in an exception
                    try
                    {
                        await this.BatchManagementClient.BatchAccount.GetAsync(resourceGroupName, batchAccountName);
                    }
                    catch (CloudException ex)
                    {
                        Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode);
                    }
                }
                finally
                {
                    await this.ResourceManagementClient.ResourceGroups.DeleteWithHttpMessagesAsync(resourceGroupName);
                }
            }
        }
        public async Task BatchAccountCanCreateWithBYOSEnabled()
        {
            using (MockContext context = StartMockContextAndInitializeClients(this.GetType().FullName))
            {
                string        resourceGroupName = TestUtilities.GenerateName();
                string        batchAccountName  = TestUtilities.GenerateName();
                string        keyvaultName      = TestUtilities.GenerateName();
                ResourceGroup group             = new ResourceGroup(this.Location);
                await this.ResourceManagementClient.ResourceGroups.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, group);

                try
                {
                    //Register with keyvault just in case we haven't already
                    await this.ResourceManagementClient.Providers.RegisterWithHttpMessagesAsync("Microsoft.KeyVault");

                    var result = await this.ResourceManagementClient.Resources.CreateOrUpdateWithHttpMessagesAsync(
                        resourceGroupName : resourceGroupName,
                        resourceProviderNamespace : "Microsoft.KeyVault",
                        parentResourcePath : "",
                        resourceType : "vaults",
                        resourceName : keyvaultName,
                        apiVersion : "2016-10-01",
                        parameters : new GenericResource()
                    {
                        Location   = this.Location,
                        Properties = new Dictionary <string, object>
                        {
                            { "tenantId", "72f988bf-86f1-41af-91ab-2d7cd011db47" },
                            { "sku", new Dictionary <string, object> {
                                  { "family", "A" }, { "name", "standard" }
                              } },
                            { "accessPolicies", new []
                              {
                                  new Dictionary <string, object>
                                  {
                                      { "objectId", "f520d84c-3fd3-4cc8-88d4-2ed25b00d27a" },
                                      { "tenantId", "72f988bf-86f1-41af-91ab-2d7cd011db47" },
                                      { "permissions", new Dictionary <string, object>
                                            {
                                                { "secrets", new [] { "All" } },
                                                { "keys", new [] { "All" } },
                                            } }
                                  }
                              } },
                            { "enabledForDeployment", true },
                            { "enabledForTemplateDeployment", true },
                            { "enabledForDiskEncryption", true }
                        }
                    });

                    var keyVaultReferenceId =
                        $"/subscriptions/{this.BatchManagementClient.SubscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{keyvaultName}";
                    var keyVaultReferenceUrl = ((Newtonsoft.Json.Linq.JObject)result.Body.Properties)["vaultUri"].ToString();
                    // Create an account
                    BatchAccountCreateParameters createParams = new BatchAccountCreateParameters(
                        this.Location,
                        poolAllocationMode: PoolAllocationMode.UserSubscription,
                        keyVaultReference: new KeyVaultReference(
                            keyVaultReferenceId,
                            keyVaultReferenceUrl));

                    await this.BatchManagementClient.BatchAccount.CreateAsync(resourceGroupName, batchAccountName, createParams);

                    // Get the account and verify some properties
                    BatchAccount batchAccount = await this.BatchManagementClient.BatchAccount.GetAsync(resourceGroupName, batchAccountName);

                    Assert.Equal(batchAccountName, batchAccount.Name);
                    Assert.Null(batchAccount.DedicatedCoreQuota);
                    Assert.Null(batchAccount.DedicatedCoreQuotaPerVMFamily);
                    Assert.False(batchAccount.DedicatedCoreQuotaPerVMFamilyEnforced); // TODO: change this when pfq enforcement happens
                    Assert.Null(batchAccount.LowPriorityCoreQuota);
                    Assert.Equal(PoolAllocationMode.UserSubscription, batchAccount.PoolAllocationMode);
                    Assert.Equal(keyVaultReferenceId, batchAccount.KeyVaultReference.Id);
                    Assert.Equal(keyVaultReferenceUrl, batchAccount.KeyVaultReference.Url);
                }
                finally
                {
                    await this.ResourceManagementClient.ResourceGroups.DeleteWithHttpMessagesAsync(resourceGroupName);
                }
            }
        }
 /// <summary>
 /// Begin creating the batch account.To determine whether the operation
 /// has finished processing the request, call
 /// GetLongRunningOperationStatus.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Batch.IAccountOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group that contains the new
 /// Batch account.
 /// </param>
 /// <param name='accountName'>
 /// Required. A name for the Batch account which must be unique within
 /// Azure. Batch account names must be between 3 and 24 characters in
 /// length and must use only numbers and lower-case letters. This name
 /// is used as part of the DNS name that is used to access the batch
 /// service in the region in which the account is created. For
 /// example: http://AccountName.batch.core.windows.net/.
 /// </param>
 /// <param name='parameters'>
 /// Required. Additional parameters for account creation
 /// </param>
 /// <returns>
 /// Values returned by the Create operation.
 /// </returns>
 public static Task <BatchAccountCreateResponse> BeginCreatingAsync(this IAccountOperations operations, string resourceGroupName, string accountName, BatchAccountCreateParameters parameters)
 {
     return(operations.BeginCreatingAsync(resourceGroupName, accountName, parameters, CancellationToken.None));
 }
 /// <summary>
 /// Begin creating the batch account.To determine whether the operation
 /// has finished processing the request, call
 /// GetLongRunningOperationStatus.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.Batch.IAccountOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The name of the resource group that contains the new
 /// Batch account.
 /// </param>
 /// <param name='accountName'>
 /// Required. A name for the Batch account which must be unique within
 /// Azure. Batch account names must be between 3 and 24 characters in
 /// length and must use only numbers and lower-case letters. This name
 /// is used as part of the DNS name that is used to access the batch
 /// service in the region in which the account is created. For
 /// example: http://AccountName.batch.core.windows.net/.
 /// </param>
 /// <param name='parameters'>
 /// Required. Additional parameters for account creation
 /// </param>
 /// <returns>
 /// Values returned by the Create operation.
 /// </returns>
 public static BatchAccountCreateResponse BeginCreating(this IAccountOperations operations, string resourceGroupName, string accountName, BatchAccountCreateParameters parameters)
 {
     return(Task.Factory.StartNew((object s) =>
     {
         return ((IAccountOperations)s).BeginCreatingAsync(resourceGroupName, accountName, parameters);
     }
                                  , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
 }
Exemplo n.º 14
0
        public async Task BatchPoolEndToEndAsync()
        {
            using (MockContext context = StartMockContextAndInitializeClients(this.GetType().FullName))
            {
                string        resourceGroupName = TestUtilities.GenerateName();
                string        batchAccountName  = TestUtilities.GenerateName();
                string        paasPoolName      = "test_paas_pool";
                string        iaasPoolName      = "test_iaas_pool";
                ResourceGroup group             = new ResourceGroup(this.Location);
                await this.ResourceManagementClient.ResourceGroups.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, group);

                // Create an account
                BatchAccountCreateParameters createParams = new BatchAccountCreateParameters(this.Location);
                await this.BatchManagementClient.BatchAccount.CreateAsync(resourceGroupName, batchAccountName, createParams);

                try
                {
                    // Create PaaS pool
                    Pool paasPool = new Pool();
                    paasPool.DisplayName             = "test_pool";
                    paasPool.VmSize                  = "small";
                    paasPool.DeploymentConfiguration = new DeploymentConfiguration()
                    {
                        CloudServiceConfiguration = new CloudServiceConfiguration()
                        {
                            OsFamily = "5"
                        }
                    };
                    var resources = new List <ResourceFile>();
                    resources.Add(new ResourceFile(httpUrl: "https://blobsource.com", filePath: "filename.txt"));
                    var environments = new List <EnvironmentSetting>();
                    environments.Add(new EnvironmentSetting("ENV_VAR", "env_value"));
                    paasPool.StartTask = new StartTask()
                    {
                        CommandLine         = "cmd.exe /c \"echo hello world\"",
                        ResourceFiles       = resources,
                        EnvironmentSettings = environments,
                        UserIdentity        = new UserIdentity()
                        {
                            AutoUser = new AutoUserSpecification()
                            {
                                ElevationLevel = ElevationLevel.Admin
                            }
                        }
                    };
                    var accounts = new List <UserAccount>();
                    accounts.Add(new UserAccount("username", "randompasswd"));
                    paasPool.UserAccounts  = accounts;
                    paasPool.ScaleSettings = new ScaleSettings()
                    {
                        FixedScale = new FixedScaleSettings()
                        {
                            TargetDedicatedNodes   = 0,
                            TargetLowPriorityNodes = 0
                        }
                    };

                    var paasPoolResponse = await this.BatchManagementClient.Pool.CreateAsync(resourceGroupName, batchAccountName, paasPoolName, paasPool);

                    Assert.NotNull(paasPoolResponse.StartTask);
                    var referenceId =
                        $"/subscriptions/{this.BatchManagementClient.SubscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{batchAccountName}/pools/{paasPoolName.ToLowerInvariant()}";
                    Assert.Equal(referenceId, paasPoolResponse.Id);

                    // Create IaaS pool
                    Pool iaasPool = new Pool();
                    iaasPool.DisplayName             = "test_pool";
                    iaasPool.VmSize                  = "Standard_A1";
                    iaasPool.DeploymentConfiguration = new DeploymentConfiguration()
                    {
                        VirtualMachineConfiguration = new VirtualMachineConfiguration()
                        {
                            ImageReference = new ImageReference()
                            {
                                Publisher = "MicrosoftWindowsServer",
                                Offer     = "WindowsServer",
                                Sku       = "2016-Datacenter-smalldisk"
                            },
                            NodeAgentSkuId       = "batch.node.windows amd64",
                            WindowsConfiguration = new WindowsConfiguration(true)
                        }
                    };
                    iaasPool.ScaleSettings = new ScaleSettings()
                    {
                        FixedScale = new FixedScaleSettings()
                        {
                            TargetDedicatedNodes   = 0,
                            TargetLowPriorityNodes = 0
                        }
                    };

                    var iaasPoolResponse = await this.BatchManagementClient.Pool.CreateAsync(resourceGroupName, batchAccountName, iaasPoolName, iaasPool);

                    Assert.Null(iaasPoolResponse.StartTask);
                    referenceId =
                        $"/subscriptions/{this.BatchManagementClient.SubscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{batchAccountName}/pools/{iaasPoolName.ToLowerInvariant()}";
                    Assert.Equal(referenceId, iaasPoolResponse.Id);

                    // Verify list operation
                    var pools = await this.BatchManagementClient.Pool.ListByBatchAccountAsync(resourceGroupName, batchAccountName);

                    Assert.Equal(2, pools.Count());

                    // Verify get operation
                    var pool = await this.BatchManagementClient.Pool.GetAsync(resourceGroupName, batchAccountName, iaasPoolName);

                    Assert.Equal("STANDARD_A1", pool.VmSize);
                    Assert.Null(pool.DisplayName);
                    Assert.Equal(AllocationState.Steady, pool.AllocationState);
                    Assert.Equal("batch.node.windows amd64", pool.DeploymentConfiguration.VirtualMachineConfiguration.NodeAgentSkuId);

                    // Verify stop resize operation
                    await this.BatchManagementClient.Pool.StopResizeAsync(resourceGroupName, batchAccountName, iaasPoolName);

                    // Verify disable auto scale operation
                    await this.BatchManagementClient.Pool.DisableAutoScaleAsync(resourceGroupName, batchAccountName, iaasPoolName);

                    // Delete the paas pool
                    try
                    {
                        await this.BatchManagementClient.Pool.DeleteAsync(resourceGroupName, batchAccountName, paasPoolName);
                    }
                    catch (CloudException ex)
                    {
                        if (ex.Response.StatusCode != HttpStatusCode.NotFound)
                        {
                            throw;
                        }
                    }

                    // Delete iaaS pool
                    try
                    {
                        await this.BatchManagementClient.Pool.DeleteAsync(resourceGroupName, batchAccountName, iaasPoolName);
                    }
                    catch (CloudException ex)
                    {
                        if (ex.Response.StatusCode != HttpStatusCode.NotFound)
                        {
                            throw;
                        }
                    }

                    // Verify pool was deleted. A GET operation will return a 404 error and result in an exception
                    try
                    {
                        await this.BatchManagementClient.Pool.GetAsync(resourceGroupName, batchAccountName, paasPoolName);
                    }
                    catch (CloudException ex)
                    {
                        Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode);
                    }
                }
                finally
                {
                    await this.BatchManagementClient.BatchAccount.DeleteAsync(resourceGroupName, batchAccountName);

                    await this.ResourceManagementClient.ResourceGroups.DeleteWithHttpMessagesAsync(resourceGroupName);
                }
            }
        }
Exemplo n.º 15
0
 /// <summary>
 /// Creates a new Batch account with the specified parameters. Existing
 /// accounts cannot be updated with this API and should instead be updated
 /// with the Update Batch Account API.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group that contains the new Batch account.
 /// </param>
 /// <param name='accountName'>
 /// A name for the Batch account which must be unique within the region. Batch
 /// account names must be between 3 and 24 characters in length and must use
 /// only numbers and lowercase letters. This name is used as part of the DNS
 /// name that is used to access the Batch service in the region in which the
 /// account is created. For example:
 /// http://accountname.region.batch.azure.com/.
 /// </param>
 /// <param name='parameters'>
 /// Additional parameters for account creation.
 /// </param>
 public static AccountResource Create(this IAccountOperations operations, string resourceGroupName, string accountName, BatchAccountCreateParameters parameters)
 {
     return(Task.Factory.StartNew(s => ((IAccountOperations)s).CreateAsync(resourceGroupName, accountName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
 }