From c9c6bf46679c9f1c1afc435746677985bee4da32 Mon Sep 17 00:00:00 2001 From: Julien Corioland Date: Mon, 3 Dec 2018 11:18:12 +0100 Subject: [PATCH 01/13] add examples for future batch support --- examples/batch/README.md | 16 ++++++++++++++ examples/batch/main.tf | 37 +++++++++++++++++++++++++++++++ examples/batch/variables.tf | 44 +++++++++++++++++++++++++++++++++++++ 3 files changed, 97 insertions(+) create mode 100644 examples/batch/README.md create mode 100644 examples/batch/main.tf create mode 100644 examples/batch/variables.tf diff --git a/examples/batch/README.md b/examples/batch/README.md new file mode 100644 index 000000000000..deb0f4d3f877 --- /dev/null +++ b/examples/batch/README.md @@ -0,0 +1,16 @@ +# Azure Batch Sample + +Sample to deploy a Job in Azure Batch + +## Creates + +1. A Resource Group +2. A [Storage Account](https://docs.microsoft.com/en-us/azure/batch/batch-api-basics#azure-storage-account) +3. A [Batch Account](https://docs.microsoft.com/en-us/azure/batch/batch-api-basics#account) +4. A [Pool](https://docs.microsoft.com/en-us/azure/batch/batch-api-basics#pool) of compute nodes + +## Usage + +- Provide values to all variables (credentials and names). +- Create with `terraform apply` +- Destroy all with `terraform destroy --force` diff --git a/examples/batch/main.tf b/examples/batch/main.tf new file mode 100644 index 000000000000..2e760e14ffe1 --- /dev/null +++ b/examples/batch/main.tf @@ -0,0 +1,37 @@ +# Configure the Microsoft Azure Provider +provider "azurerm" { + # if you're using a Service Principal (shared account) then either set the environment variables, or fill these in: # subscription_id = "..." # client_id = "..." # client_secret = "..." # tenant_id = "..." +} + +resource "azurerm_resource_group" "rg" { + name = "${var.resource_group_name}" + location = "${var.location}" +} + +resource "random_integer" "ri" { + min = 10000 + max = 99999 +} + +resource "azurerm_storage_account" "stor" { + name = "stor${random_integer.ri.result}" + resource_group_name = "${azurerm_resource_group.rg.name}" + location = "${azurerm_resource_group.rg.location}" + account_tier = "${var.storage_account_tier}" + account_replication_type = "${var.storage_replication_type}" +} + +resource "azurerm_batch_account" "batch" { + name = "batch${random_integer.ri.result}" + resource_group_name = "${azurerm_resource_group.rg.name}" + location = "${azurerm_resource_group.rg.location}" + storage_account_name = "${azurerm_storage_account.stor.name}" +} + +resource "azurerm_batch_pool" "pool" { + id = "pool${random_integer.ri.result}" + vm_size = "${var.batch_pool_nodes_vm_size}" + target_dedicated_node = "${var.batch_pool_nodes_count}" + vm_image = "${var.batch_pool_nodes_vm_image}" + node_agent_sku_id = "${var.batch.pool_nodes_agent_sku_id}" +} \ No newline at end of file diff --git a/examples/batch/variables.tf b/examples/batch/variables.tf new file mode 100644 index 000000000000..93343cdf49a5 --- /dev/null +++ b/examples/batch/variables.tf @@ -0,0 +1,44 @@ +variable "resource_group_name" { + type = "string" + description = "Name of the azure resource group." + default = "tfex-batch" +} + +variable "location" { + type = "string" + description = "Location of the azure resource group." + default = "westeurope" +} + +variable "storage_account_tier" { + description = "Defines the Tier of storage account to be created. Valid options are Standard and Premium." + default = "Standard" +} + +variable "storage_replication_type" { + description = "Defines the Replication Type to use for this storage account. Valid options include LRS, GRS etc." + default = "LRS" +} + +variable "batch_pool_nodes_vm_size" { + description = "Size of the virtual machines in the nodes pool" + default = "Standard_A1_v2" +} + +variable "batch_pool_nodes_count" { + description = "Number of virtual machines in the nodes pool" + default = 2 +} + +variable "batch_pool_nodes_vm_image" { + description = "Virtual machine image to use for the nodes in the pool" + default = "canonical:ubuntuserver:16.04-LTS" +} + +variable "batch_pool_nodes_agent_sku_id" { + description = "Agent Sku to use for the nodes in the pool" + default = "batch.node.ubuntu 16.04" +} + + + From e6918708487ed4e547b34c8c1cf01de5bc2027f2 Mon Sep 17 00:00:00 2001 From: Julien Corioland Date: Mon, 3 Dec 2018 15:28:10 +0100 Subject: [PATCH 02/13] add Azure Batch Go SDK to vendor --- .../batch/mgmt/2017-09-01/batch/account.go | 781 ++++++ .../mgmt/2017-09-01/batch/application.go | 463 ++++ .../2017-09-01/batch/applicationpackage.go | 360 +++ .../mgmt/2017-09-01/batch/certificate.go | 606 +++++ .../batch/mgmt/2017-09-01/batch/client.go | 51 + .../batch/mgmt/2017-09-01/batch/location.go | 181 ++ .../batch/mgmt/2017-09-01/batch/models.go | 2152 +++++++++++++++++ .../batch/mgmt/2017-09-01/batch/operations.go | 126 + .../batch/mgmt/2017-09-01/batch/pool.go | 717 ++++++ .../batch/mgmt/2017-09-01/batch/version.go | 30 + vendor/vendor.json | 8 + 11 files changed, 5475 insertions(+) create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/account.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/application.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/applicationpackage.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/certificate.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/location.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/models.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/operations.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/pool.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/version.go diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/account.go b/vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/account.go new file mode 100644 index 000000000000..ebc60a38765b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/account.go @@ -0,0 +1,781 @@ +package batch + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// AccountClient is the client for the Account methods of the Batch service. +type AccountClient struct { + BaseClient +} + +// NewAccountClient creates an instance of the AccountClient client. +func NewAccountClient(subscriptionID string) AccountClient { + return NewAccountClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewAccountClientWithBaseURI creates an instance of the AccountClient client. +func NewAccountClientWithBaseURI(baseURI string, subscriptionID string) AccountClient { + return AccountClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Create 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. +// Parameters: +// resourceGroupName - the name of the resource group that contains the Batch account. +// 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/. +// parameters - additional parameters for account creation. +func (client AccountClient) Create(ctx context.Context, resourceGroupName string, accountName string, parameters AccountCreateParameters) (result AccountCreateFuture, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}, + {Target: "accountName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}, + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.Location", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.AccountCreateProperties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.AccountCreateProperties.AutoStorage", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.AccountCreateProperties.AutoStorage.StorageAccountID", Name: validation.Null, Rule: true, Chain: nil}}}, + {Target: "parameters.AccountCreateProperties.KeyVaultReference", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.AccountCreateProperties.KeyVaultReference.ID", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.AccountCreateProperties.KeyVaultReference.URL", Name: validation.Null, Rule: true, Chain: nil}, + }}, + }}}}}); err != nil { + return result, validation.NewError("batch.AccountClient", "Create", err.Error()) + } + + req, err := client.CreatePreparer(ctx, resourceGroupName, accountName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.AccountClient", "Create", nil, "Failure preparing request") + return + } + + result, err = client.CreateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.AccountClient", "Create", result.Response(), "Failure sending request") + return + } + + return +} + +// CreatePreparer prepares the Create request. +func (client AccountClient) CreatePreparer(ctx context.Context, resourceGroupName string, accountName string, parameters AccountCreateParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateSender sends the Create request. The method will close the +// http.Response Body if it receives an error. +func (client AccountClient) CreateSender(req *http.Request) (future AccountCreateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// CreateResponder handles the response to the Create request. The method always +// closes the http.Response Body. +func (client AccountClient) CreateResponder(resp *http.Response) (result Account, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes the specified Batch account. +// Parameters: +// resourceGroupName - the name of the resource group that contains the Batch account. +// accountName - the name of the Batch account. +func (client AccountClient) Delete(ctx context.Context, resourceGroupName string, accountName string) (result AccountDeleteFuture, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}, + {Target: "accountName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("batch.AccountClient", "Delete", err.Error()) + } + + req, err := client.DeletePreparer(ctx, resourceGroupName, accountName) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.AccountClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.AccountClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client AccountClient) DeletePreparer(ctx context.Context, resourceGroupName string, accountName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client AccountClient) DeleteSender(req *http.Request) (future AccountDeleteFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client AccountClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets information about the specified Batch account. +// Parameters: +// resourceGroupName - the name of the resource group that contains the Batch account. +// accountName - the name of the Batch account. +func (client AccountClient) Get(ctx context.Context, resourceGroupName string, accountName string) (result Account, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}, + {Target: "accountName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("batch.AccountClient", "Get", err.Error()) + } + + req, err := client.GetPreparer(ctx, resourceGroupName, accountName) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.AccountClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "batch.AccountClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.AccountClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client AccountClient) GetPreparer(ctx context.Context, resourceGroupName string, accountName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client AccountClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client AccountClient) GetResponder(resp *http.Response) (result Account, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetKeys this operation applies only to Batch accounts created with a poolAllocationMode of 'BatchService'. If the +// Batch account was created with a poolAllocationMode of 'UserSubscription', clients cannot use access to keys to +// authenticate, and must use Azure Active Directory instead. In this case, getting the keys will fail. +// Parameters: +// resourceGroupName - the name of the resource group that contains the Batch account. +// accountName - the name of the Batch account. +func (client AccountClient) GetKeys(ctx context.Context, resourceGroupName string, accountName string) (result AccountKeys, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}, + {Target: "accountName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("batch.AccountClient", "GetKeys", err.Error()) + } + + req, err := client.GetKeysPreparer(ctx, resourceGroupName, accountName) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.AccountClient", "GetKeys", nil, "Failure preparing request") + return + } + + resp, err := client.GetKeysSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "batch.AccountClient", "GetKeys", resp, "Failure sending request") + return + } + + result, err = client.GetKeysResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.AccountClient", "GetKeys", resp, "Failure responding to request") + } + + return +} + +// GetKeysPreparer prepares the GetKeys request. +func (client AccountClient) GetKeysPreparer(ctx context.Context, resourceGroupName string, accountName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/listKeys", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetKeysSender sends the GetKeys request. The method will close the +// http.Response Body if it receives an error. +func (client AccountClient) GetKeysSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetKeysResponder handles the response to the GetKeys request. The method always +// closes the http.Response Body. +func (client AccountClient) GetKeysResponder(resp *http.Response) (result AccountKeys, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List gets information about the Batch accounts associated with the subscription. +func (client AccountClient) List(ctx context.Context) (result AccountListResultPage, err error) { + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.AccountClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.alr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "batch.AccountClient", "List", resp, "Failure sending request") + return + } + + result.alr, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.AccountClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client AccountClient) ListPreparer(ctx context.Context) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Batch/batchAccounts", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client AccountClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client AccountClient) ListResponder(resp *http.Response) (result AccountListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listNextResults retrieves the next set of results, if any. +func (client AccountClient) listNextResults(lastResults AccountListResult) (result AccountListResult, err error) { + req, err := lastResults.accountListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "batch.AccountClient", "listNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "batch.AccountClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.AccountClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client AccountClient) ListComplete(ctx context.Context) (result AccountListResultIterator, err error) { + result.page, err = client.List(ctx) + return +} + +// ListByResourceGroup gets information about the Batch accounts associated with the specified resource group. +// Parameters: +// resourceGroupName - the name of the resource group that contains the Batch account. +func (client AccountClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result AccountListResultPage, err error) { + result.fn = client.listByResourceGroupNextResults + req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.AccountClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.alr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "batch.AccountClient", "ListByResourceGroup", resp, "Failure sending request") + return + } + + result.alr, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.AccountClient", "ListByResourceGroup", resp, "Failure responding to request") + } + + return +} + +// ListByResourceGroupPreparer prepares the ListByResourceGroup request. +func (client AccountClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the +// http.Response Body if it receives an error. +func (client AccountClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always +// closes the http.Response Body. +func (client AccountClient) ListByResourceGroupResponder(resp *http.Response) (result AccountListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByResourceGroupNextResults retrieves the next set of results, if any. +func (client AccountClient) listByResourceGroupNextResults(lastResults AccountListResult) (result AccountListResult, err error) { + req, err := lastResults.accountListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "batch.AccountClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "batch.AccountClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.AccountClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. +func (client AccountClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result AccountListResultIterator, err error) { + result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) + return +} + +// RegenerateKey regenerates the specified account key for the Batch account. +// Parameters: +// resourceGroupName - the name of the resource group that contains the Batch account. +// accountName - the name of the Batch account. +// parameters - the type of key to regenerate. +func (client AccountClient) RegenerateKey(ctx context.Context, resourceGroupName string, accountName string, parameters AccountRegenerateKeyParameters) (result AccountKeys, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}, + {Target: "accountName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("batch.AccountClient", "RegenerateKey", err.Error()) + } + + req, err := client.RegenerateKeyPreparer(ctx, resourceGroupName, accountName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.AccountClient", "RegenerateKey", nil, "Failure preparing request") + return + } + + resp, err := client.RegenerateKeySender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "batch.AccountClient", "RegenerateKey", resp, "Failure sending request") + return + } + + result, err = client.RegenerateKeyResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.AccountClient", "RegenerateKey", resp, "Failure responding to request") + } + + return +} + +// RegenerateKeyPreparer prepares the RegenerateKey request. +func (client AccountClient) RegenerateKeyPreparer(ctx context.Context, resourceGroupName string, accountName string, parameters AccountRegenerateKeyParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/regenerateKeys", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// RegenerateKeySender sends the RegenerateKey request. The method will close the +// http.Response Body if it receives an error. +func (client AccountClient) RegenerateKeySender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// RegenerateKeyResponder handles the response to the RegenerateKey request. The method always +// closes the http.Response Body. +func (client AccountClient) RegenerateKeyResponder(resp *http.Response) (result AccountKeys, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// SynchronizeAutoStorageKeys synchronizes access keys for the auto-storage account configured for the specified Batch +// account. +// Parameters: +// resourceGroupName - the name of the resource group that contains the Batch account. +// accountName - the name of the Batch account. +func (client AccountClient) SynchronizeAutoStorageKeys(ctx context.Context, resourceGroupName string, accountName string) (result autorest.Response, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}, + {Target: "accountName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("batch.AccountClient", "SynchronizeAutoStorageKeys", err.Error()) + } + + req, err := client.SynchronizeAutoStorageKeysPreparer(ctx, resourceGroupName, accountName) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.AccountClient", "SynchronizeAutoStorageKeys", nil, "Failure preparing request") + return + } + + resp, err := client.SynchronizeAutoStorageKeysSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "batch.AccountClient", "SynchronizeAutoStorageKeys", resp, "Failure sending request") + return + } + + result, err = client.SynchronizeAutoStorageKeysResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.AccountClient", "SynchronizeAutoStorageKeys", resp, "Failure responding to request") + } + + return +} + +// SynchronizeAutoStorageKeysPreparer prepares the SynchronizeAutoStorageKeys request. +func (client AccountClient) SynchronizeAutoStorageKeysPreparer(ctx context.Context, resourceGroupName string, accountName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/syncAutoStorageKeys", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// SynchronizeAutoStorageKeysSender sends the SynchronizeAutoStorageKeys request. The method will close the +// http.Response Body if it receives an error. +func (client AccountClient) SynchronizeAutoStorageKeysSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// SynchronizeAutoStorageKeysResponder handles the response to the SynchronizeAutoStorageKeys request. The method always +// closes the http.Response Body. +func (client AccountClient) SynchronizeAutoStorageKeysResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Update updates the properties of an existing Batch account. +// Parameters: +// resourceGroupName - the name of the resource group that contains the Batch account. +// accountName - the name of the Batch account. +// parameters - additional parameters for account update. +func (client AccountClient) Update(ctx context.Context, resourceGroupName string, accountName string, parameters AccountUpdateParameters) (result Account, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}, + {Target: "accountName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("batch.AccountClient", "Update", err.Error()) + } + + req, err := client.UpdatePreparer(ctx, resourceGroupName, accountName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.AccountClient", "Update", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "batch.AccountClient", "Update", resp, "Failure sending request") + return + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.AccountClient", "Update", resp, "Failure responding to request") + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client AccountClient) UpdatePreparer(ctx context.Context, resourceGroupName string, accountName string, parameters AccountUpdateParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// UpdateSender sends the Update request. The method will close the +// http.Response Body if it receives an error. +func (client AccountClient) UpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client AccountClient) UpdateResponder(resp *http.Response) (result Account, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/application.go b/vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/application.go new file mode 100644 index 000000000000..170e7bb1195d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/application.go @@ -0,0 +1,463 @@ +package batch + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// ApplicationClient is the client for the Application methods of the Batch service. +type ApplicationClient struct { + BaseClient +} + +// NewApplicationClient creates an instance of the ApplicationClient client. +func NewApplicationClient(subscriptionID string) ApplicationClient { + return NewApplicationClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewApplicationClientWithBaseURI creates an instance of the ApplicationClient client. +func NewApplicationClientWithBaseURI(baseURI string, subscriptionID string) ApplicationClient { + return ApplicationClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Create adds an application to the specified Batch account. +// Parameters: +// resourceGroupName - the name of the resource group that contains the Batch account. +// accountName - the name of the Batch account. +// applicationID - the ID of the application. +// parameters - the parameters for the request. +func (client ApplicationClient) Create(ctx context.Context, resourceGroupName string, accountName string, applicationID string, parameters *ApplicationCreateParameters) (result Application, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}, + {Target: "accountName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("batch.ApplicationClient", "Create", err.Error()) + } + + req, err := client.CreatePreparer(ctx, resourceGroupName, accountName, applicationID, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.ApplicationClient", "Create", nil, "Failure preparing request") + return + } + + resp, err := client.CreateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "batch.ApplicationClient", "Create", resp, "Failure sending request") + return + } + + result, err = client.CreateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.ApplicationClient", "Create", resp, "Failure responding to request") + } + + return +} + +// CreatePreparer prepares the Create request. +func (client ApplicationClient) CreatePreparer(ctx context.Context, resourceGroupName string, accountName string, applicationID string, parameters *ApplicationCreateParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "applicationId": autorest.Encode("path", applicationID), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationId}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + if parameters != nil { + preparer = autorest.DecoratePreparer(preparer, + autorest.WithJSON(parameters)) + } + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateSender sends the Create request. The method will close the +// http.Response Body if it receives an error. +func (client ApplicationClient) CreateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CreateResponder handles the response to the Create request. The method always +// closes the http.Response Body. +func (client ApplicationClient) CreateResponder(resp *http.Response) (result Application, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes an application. +// Parameters: +// resourceGroupName - the name of the resource group that contains the Batch account. +// accountName - the name of the Batch account. +// applicationID - the ID of the application. +func (client ApplicationClient) Delete(ctx context.Context, resourceGroupName string, accountName string, applicationID string) (result autorest.Response, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}, + {Target: "accountName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("batch.ApplicationClient", "Delete", err.Error()) + } + + req, err := client.DeletePreparer(ctx, resourceGroupName, accountName, applicationID) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.ApplicationClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "batch.ApplicationClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.ApplicationClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client ApplicationClient) DeletePreparer(ctx context.Context, resourceGroupName string, accountName string, applicationID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "applicationId": autorest.Encode("path", applicationID), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationId}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client ApplicationClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ApplicationClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets information about the specified application. +// Parameters: +// resourceGroupName - the name of the resource group that contains the Batch account. +// accountName - the name of the Batch account. +// applicationID - the ID of the application. +func (client ApplicationClient) Get(ctx context.Context, resourceGroupName string, accountName string, applicationID string) (result Application, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}, + {Target: "accountName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("batch.ApplicationClient", "Get", err.Error()) + } + + req, err := client.GetPreparer(ctx, resourceGroupName, accountName, applicationID) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.ApplicationClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "batch.ApplicationClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.ApplicationClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client ApplicationClient) GetPreparer(ctx context.Context, resourceGroupName string, accountName string, applicationID string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "applicationId": autorest.Encode("path", applicationID), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationId}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client ApplicationClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ApplicationClient) GetResponder(resp *http.Response) (result Application, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List lists all of the applications in the specified account. +// Parameters: +// resourceGroupName - the name of the resource group that contains the Batch account. +// accountName - the name of the Batch account. +// maxresults - the maximum number of items to return in the response. +func (client ApplicationClient) List(ctx context.Context, resourceGroupName string, accountName string, maxresults *int32) (result ListApplicationsResultPage, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}, + {Target: "accountName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("batch.ApplicationClient", "List", err.Error()) + } + + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, accountName, maxresults) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.ApplicationClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.lar.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "batch.ApplicationClient", "List", resp, "Failure sending request") + return + } + + result.lar, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.ApplicationClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client ApplicationClient) ListPreparer(ctx context.Context, resourceGroupName string, accountName string, maxresults *int32) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if maxresults != nil { + queryParameters["maxresults"] = autorest.Encode("query", *maxresults) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client ApplicationClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client ApplicationClient) ListResponder(resp *http.Response) (result ListApplicationsResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listNextResults retrieves the next set of results, if any. +func (client ApplicationClient) listNextResults(lastResults ListApplicationsResult) (result ListApplicationsResult, err error) { + req, err := lastResults.listApplicationsResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "batch.ApplicationClient", "listNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "batch.ApplicationClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.ApplicationClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client ApplicationClient) ListComplete(ctx context.Context, resourceGroupName string, accountName string, maxresults *int32) (result ListApplicationsResultIterator, err error) { + result.page, err = client.List(ctx, resourceGroupName, accountName, maxresults) + return +} + +// Update updates settings for the specified application. +// Parameters: +// resourceGroupName - the name of the resource group that contains the Batch account. +// accountName - the name of the Batch account. +// applicationID - the ID of the application. +// parameters - the parameters for the request. +func (client ApplicationClient) Update(ctx context.Context, resourceGroupName string, accountName string, applicationID string, parameters ApplicationUpdateParameters) (result autorest.Response, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}, + {Target: "accountName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("batch.ApplicationClient", "Update", err.Error()) + } + + req, err := client.UpdatePreparer(ctx, resourceGroupName, accountName, applicationID, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.ApplicationClient", "Update", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "batch.ApplicationClient", "Update", resp, "Failure sending request") + return + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.ApplicationClient", "Update", resp, "Failure responding to request") + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client ApplicationClient) UpdatePreparer(ctx context.Context, resourceGroupName string, accountName string, applicationID string, parameters ApplicationUpdateParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "applicationId": autorest.Encode("path", applicationID), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationId}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// UpdateSender sends the Update request. The method will close the +// http.Response Body if it receives an error. +func (client ApplicationClient) UpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client ApplicationClient) UpdateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/applicationpackage.go b/vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/applicationpackage.go new file mode 100644 index 000000000000..c61bb8addfc4 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/applicationpackage.go @@ -0,0 +1,360 @@ +package batch + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// ApplicationPackageClient is the client for the ApplicationPackage methods of the Batch service. +type ApplicationPackageClient struct { + BaseClient +} + +// NewApplicationPackageClient creates an instance of the ApplicationPackageClient client. +func NewApplicationPackageClient(subscriptionID string) ApplicationPackageClient { + return NewApplicationPackageClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewApplicationPackageClientWithBaseURI creates an instance of the ApplicationPackageClient client. +func NewApplicationPackageClientWithBaseURI(baseURI string, subscriptionID string) ApplicationPackageClient { + return ApplicationPackageClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Activate activates the specified application package. +// Parameters: +// resourceGroupName - the name of the resource group that contains the Batch account. +// accountName - the name of the Batch account. +// applicationID - the ID of the application. +// version - the version of the application to activate. +// parameters - the parameters for the request. +func (client ApplicationPackageClient) Activate(ctx context.Context, resourceGroupName string, accountName string, applicationID string, version string, parameters ActivateApplicationPackageParameters) (result autorest.Response, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}, + {Target: "accountName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}, + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.Format", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("batch.ApplicationPackageClient", "Activate", err.Error()) + } + + req, err := client.ActivatePreparer(ctx, resourceGroupName, accountName, applicationID, version, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.ApplicationPackageClient", "Activate", nil, "Failure preparing request") + return + } + + resp, err := client.ActivateSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "batch.ApplicationPackageClient", "Activate", resp, "Failure sending request") + return + } + + result, err = client.ActivateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.ApplicationPackageClient", "Activate", resp, "Failure responding to request") + } + + return +} + +// ActivatePreparer prepares the Activate request. +func (client ApplicationPackageClient) ActivatePreparer(ctx context.Context, resourceGroupName string, accountName string, applicationID string, version string, parameters ActivateApplicationPackageParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "applicationId": autorest.Encode("path", applicationID), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "version": autorest.Encode("path", version), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationId}/versions/{version}/activate", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ActivateSender sends the Activate request. The method will close the +// http.Response Body if it receives an error. +func (client ApplicationPackageClient) ActivateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ActivateResponder handles the response to the Activate request. The method always +// closes the http.Response Body. +func (client ApplicationPackageClient) ActivateResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Create creates an application package record. +// Parameters: +// resourceGroupName - the name of the resource group that contains the Batch account. +// accountName - the name of the Batch account. +// applicationID - the ID of the application. +// version - the version of the application. +func (client ApplicationPackageClient) Create(ctx context.Context, resourceGroupName string, accountName string, applicationID string, version string) (result ApplicationPackage, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}, + {Target: "accountName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("batch.ApplicationPackageClient", "Create", err.Error()) + } + + req, err := client.CreatePreparer(ctx, resourceGroupName, accountName, applicationID, version) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.ApplicationPackageClient", "Create", nil, "Failure preparing request") + return + } + + resp, err := client.CreateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "batch.ApplicationPackageClient", "Create", resp, "Failure sending request") + return + } + + result, err = client.CreateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.ApplicationPackageClient", "Create", resp, "Failure responding to request") + } + + return +} + +// CreatePreparer prepares the Create request. +func (client ApplicationPackageClient) CreatePreparer(ctx context.Context, resourceGroupName string, accountName string, applicationID string, version string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "applicationId": autorest.Encode("path", applicationID), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "version": autorest.Encode("path", version), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationId}/versions/{version}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateSender sends the Create request. The method will close the +// http.Response Body if it receives an error. +func (client ApplicationPackageClient) CreateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CreateResponder handles the response to the Create request. The method always +// closes the http.Response Body. +func (client ApplicationPackageClient) CreateResponder(resp *http.Response) (result ApplicationPackage, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes an application package record and its associated binary file. +// Parameters: +// resourceGroupName - the name of the resource group that contains the Batch account. +// accountName - the name of the Batch account. +// applicationID - the ID of the application. +// version - the version of the application to delete. +func (client ApplicationPackageClient) Delete(ctx context.Context, resourceGroupName string, accountName string, applicationID string, version string) (result autorest.Response, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}, + {Target: "accountName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("batch.ApplicationPackageClient", "Delete", err.Error()) + } + + req, err := client.DeletePreparer(ctx, resourceGroupName, accountName, applicationID, version) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.ApplicationPackageClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "batch.ApplicationPackageClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.ApplicationPackageClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client ApplicationPackageClient) DeletePreparer(ctx context.Context, resourceGroupName string, accountName string, applicationID string, version string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "applicationId": autorest.Encode("path", applicationID), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "version": autorest.Encode("path", version), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationId}/versions/{version}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client ApplicationPackageClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ApplicationPackageClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets information about the specified application package. +// Parameters: +// resourceGroupName - the name of the resource group that contains the Batch account. +// accountName - the name of the Batch account. +// applicationID - the ID of the application. +// version - the version of the application. +func (client ApplicationPackageClient) Get(ctx context.Context, resourceGroupName string, accountName string, applicationID string, version string) (result ApplicationPackage, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}, + {Target: "accountName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("batch.ApplicationPackageClient", "Get", err.Error()) + } + + req, err := client.GetPreparer(ctx, resourceGroupName, accountName, applicationID, version) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.ApplicationPackageClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "batch.ApplicationPackageClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.ApplicationPackageClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client ApplicationPackageClient) GetPreparer(ctx context.Context, resourceGroupName string, accountName string, applicationID string, version string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "applicationId": autorest.Encode("path", applicationID), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "version": autorest.Encode("path", version), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationId}/versions/{version}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client ApplicationPackageClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ApplicationPackageClient) GetResponder(resp *http.Response) (result ApplicationPackage, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/certificate.go b/vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/certificate.go new file mode 100644 index 000000000000..c9ee6f1a5b37 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/certificate.go @@ -0,0 +1,606 @@ +package batch + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// CertificateClient is the client for the Certificate methods of the Batch service. +type CertificateClient struct { + BaseClient +} + +// NewCertificateClient creates an instance of the CertificateClient client. +func NewCertificateClient(subscriptionID string) CertificateClient { + return NewCertificateClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewCertificateClientWithBaseURI creates an instance of the CertificateClient client. +func NewCertificateClientWithBaseURI(baseURI string, subscriptionID string) CertificateClient { + return CertificateClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CancelDeletion if you try to delete a certificate that is being used by a pool or compute node, the status of the +// certificate changes to deleteFailed. If you decide that you want to continue using the certificate, you can use this +// operation to set the status of the certificate back to active. If you intend to delete the certificate, you do not +// need to run this operation after the deletion failed. You must make sure that the certificate is not being used by +// any resources, and then you can try again to delete the certificate. +// Parameters: +// resourceGroupName - the name of the resource group that contains the Batch account. +// accountName - the name of the Batch account. +// certificateName - the identifier for the certificate. This must be made up of algorithm and thumbprint +// separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. +func (client CertificateClient) CancelDeletion(ctx context.Context, resourceGroupName string, accountName string, certificateName string) (result Certificate, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}, + {Target: "accountName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}, + {TargetValue: certificateName, + Constraints: []validation.Constraint{{Target: "certificateName", Name: validation.MaxLength, Rule: 45, Chain: nil}, + {Target: "certificateName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "certificateName", Name: validation.Pattern, Rule: `^[\w]+-[\w]+$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("batch.CertificateClient", "CancelDeletion", err.Error()) + } + + req, err := client.CancelDeletionPreparer(ctx, resourceGroupName, accountName, certificateName) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.CertificateClient", "CancelDeletion", nil, "Failure preparing request") + return + } + + resp, err := client.CancelDeletionSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "batch.CertificateClient", "CancelDeletion", resp, "Failure sending request") + return + } + + result, err = client.CancelDeletionResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.CertificateClient", "CancelDeletion", resp, "Failure responding to request") + } + + return +} + +// CancelDeletionPreparer prepares the CancelDeletion request. +func (client CertificateClient) CancelDeletionPreparer(ctx context.Context, resourceGroupName string, accountName string, certificateName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "certificateName": autorest.Encode("path", certificateName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}/cancelDelete", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CancelDeletionSender sends the CancelDeletion request. The method will close the +// http.Response Body if it receives an error. +func (client CertificateClient) CancelDeletionSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CancelDeletionResponder handles the response to the CancelDeletion request. The method always +// closes the http.Response Body. +func (client CertificateClient) CancelDeletionResponder(resp *http.Response) (result Certificate, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Create creates a new certificate inside the specified account. +// Parameters: +// resourceGroupName - the name of the resource group that contains the Batch account. +// accountName - the name of the Batch account. +// certificateName - the identifier for the certificate. This must be made up of algorithm and thumbprint +// separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. +// parameters - additional parameters for certificate creation. +// ifMatch - the entity state (ETag) version of the certificate to update. A value of "*" can be used to apply +// the operation only if the certificate already exists. If omitted, this operation will always be applied. +// ifNoneMatch - set to '*' to allow a new certificate to be created, but to prevent updating an existing +// certificate. Other values will be ignored. +func (client CertificateClient) Create(ctx context.Context, resourceGroupName string, accountName string, certificateName string, parameters CertificateCreateOrUpdateParameters, ifMatch string, ifNoneMatch string) (result CertificateCreateFuture, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}, + {Target: "accountName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}, + {TargetValue: certificateName, + Constraints: []validation.Constraint{{Target: "certificateName", Name: validation.MaxLength, Rule: 45, Chain: nil}, + {Target: "certificateName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "certificateName", Name: validation.Pattern, Rule: `^[\w]+-[\w]+$`, Chain: nil}}}, + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.CertificateCreateOrUpdateProperties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.CertificateCreateOrUpdateProperties.Data", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil { + return result, validation.NewError("batch.CertificateClient", "Create", err.Error()) + } + + req, err := client.CreatePreparer(ctx, resourceGroupName, accountName, certificateName, parameters, ifMatch, ifNoneMatch) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.CertificateClient", "Create", nil, "Failure preparing request") + return + } + + result, err = client.CreateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.CertificateClient", "Create", result.Response(), "Failure sending request") + return + } + + return +} + +// CreatePreparer prepares the Create request. +func (client CertificateClient) CreatePreparer(ctx context.Context, resourceGroupName string, accountName string, certificateName string, parameters CertificateCreateOrUpdateParameters, ifMatch string, ifNoneMatch string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "certificateName": autorest.Encode("path", certificateName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + if len(ifMatch) > 0 { + preparer = autorest.DecoratePreparer(preparer, + autorest.WithHeader("If-Match", autorest.String(ifMatch))) + } + if len(ifNoneMatch) > 0 { + preparer = autorest.DecoratePreparer(preparer, + autorest.WithHeader("If-None-Match", autorest.String(ifNoneMatch))) + } + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateSender sends the Create request. The method will close the +// http.Response Body if it receives an error. +func (client CertificateClient) CreateSender(req *http.Request) (future CertificateCreateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// CreateResponder handles the response to the Create request. The method always +// closes the http.Response Body. +func (client CertificateClient) CreateResponder(resp *http.Response) (result Certificate, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes the specified certificate. +// Parameters: +// resourceGroupName - the name of the resource group that contains the Batch account. +// accountName - the name of the Batch account. +// certificateName - the identifier for the certificate. This must be made up of algorithm and thumbprint +// separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. +func (client CertificateClient) Delete(ctx context.Context, resourceGroupName string, accountName string, certificateName string) (result CertificateDeleteFuture, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}, + {Target: "accountName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}, + {TargetValue: certificateName, + Constraints: []validation.Constraint{{Target: "certificateName", Name: validation.MaxLength, Rule: 45, Chain: nil}, + {Target: "certificateName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "certificateName", Name: validation.Pattern, Rule: `^[\w]+-[\w]+$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("batch.CertificateClient", "Delete", err.Error()) + } + + req, err := client.DeletePreparer(ctx, resourceGroupName, accountName, certificateName) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.CertificateClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.CertificateClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client CertificateClient) DeletePreparer(ctx context.Context, resourceGroupName string, accountName string, certificateName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "certificateName": autorest.Encode("path", certificateName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client CertificateClient) DeleteSender(req *http.Request) (future CertificateDeleteFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client CertificateClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets information about the specified certificate. +// Parameters: +// resourceGroupName - the name of the resource group that contains the Batch account. +// accountName - the name of the Batch account. +// certificateName - the identifier for the certificate. This must be made up of algorithm and thumbprint +// separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. +func (client CertificateClient) Get(ctx context.Context, resourceGroupName string, accountName string, certificateName string) (result Certificate, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}, + {Target: "accountName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}, + {TargetValue: certificateName, + Constraints: []validation.Constraint{{Target: "certificateName", Name: validation.MaxLength, Rule: 45, Chain: nil}, + {Target: "certificateName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "certificateName", Name: validation.Pattern, Rule: `^[\w]+-[\w]+$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("batch.CertificateClient", "Get", err.Error()) + } + + req, err := client.GetPreparer(ctx, resourceGroupName, accountName, certificateName) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.CertificateClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "batch.CertificateClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.CertificateClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client CertificateClient) GetPreparer(ctx context.Context, resourceGroupName string, accountName string, certificateName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "certificateName": autorest.Encode("path", certificateName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client CertificateClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client CertificateClient) GetResponder(resp *http.Response) (result Certificate, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByBatchAccount lists all of the certificates in the specified account. +// Parameters: +// resourceGroupName - the name of the resource group that contains the Batch account. +// accountName - the name of the Batch account. +// maxresults - the maximum number of items to return in the response. +// selectParameter - comma separated list of properties that should be returned. e.g. +// "properties/provisioningState". Only top level properties under properties/ are valid for selection. +// filter - oData filter expression. Valid properties for filtering are "properties/provisioningState", +// "properties/provisioningStateTransitionTime", "name". +func (client CertificateClient) ListByBatchAccount(ctx context.Context, resourceGroupName string, accountName string, maxresults *int32, selectParameter string, filter string) (result ListCertificatesResultPage, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}, + {Target: "accountName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("batch.CertificateClient", "ListByBatchAccount", err.Error()) + } + + result.fn = client.listByBatchAccountNextResults + req, err := client.ListByBatchAccountPreparer(ctx, resourceGroupName, accountName, maxresults, selectParameter, filter) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.CertificateClient", "ListByBatchAccount", nil, "Failure preparing request") + return + } + + resp, err := client.ListByBatchAccountSender(req) + if err != nil { + result.lcr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "batch.CertificateClient", "ListByBatchAccount", resp, "Failure sending request") + return + } + + result.lcr, err = client.ListByBatchAccountResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.CertificateClient", "ListByBatchAccount", resp, "Failure responding to request") + } + + return +} + +// ListByBatchAccountPreparer prepares the ListByBatchAccount request. +func (client CertificateClient) ListByBatchAccountPreparer(ctx context.Context, resourceGroupName string, accountName string, maxresults *int32, selectParameter string, filter string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if maxresults != nil { + queryParameters["maxresults"] = autorest.Encode("query", *maxresults) + } + if len(selectParameter) > 0 { + queryParameters["$select"] = autorest.Encode("query", selectParameter) + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByBatchAccountSender sends the ListByBatchAccount request. The method will close the +// http.Response Body if it receives an error. +func (client CertificateClient) ListByBatchAccountSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByBatchAccountResponder handles the response to the ListByBatchAccount request. The method always +// closes the http.Response Body. +func (client CertificateClient) ListByBatchAccountResponder(resp *http.Response) (result ListCertificatesResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByBatchAccountNextResults retrieves the next set of results, if any. +func (client CertificateClient) listByBatchAccountNextResults(lastResults ListCertificatesResult) (result ListCertificatesResult, err error) { + req, err := lastResults.listCertificatesResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "batch.CertificateClient", "listByBatchAccountNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByBatchAccountSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "batch.CertificateClient", "listByBatchAccountNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByBatchAccountResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.CertificateClient", "listByBatchAccountNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByBatchAccountComplete enumerates all values, automatically crossing page boundaries as required. +func (client CertificateClient) ListByBatchAccountComplete(ctx context.Context, resourceGroupName string, accountName string, maxresults *int32, selectParameter string, filter string) (result ListCertificatesResultIterator, err error) { + result.page, err = client.ListByBatchAccount(ctx, resourceGroupName, accountName, maxresults, selectParameter, filter) + return +} + +// Update updates the properties of an existing certificate. +// Parameters: +// resourceGroupName - the name of the resource group that contains the Batch account. +// accountName - the name of the Batch account. +// certificateName - the identifier for the certificate. This must be made up of algorithm and thumbprint +// separated by a dash, and must match the certificate data in the request. For example SHA1-a3d1c5. +// parameters - certificate entity to update. +// ifMatch - the entity state (ETag) version of the certificate to update. This value can be omitted or set to +// "*" to apply the operation unconditionally. +func (client CertificateClient) Update(ctx context.Context, resourceGroupName string, accountName string, certificateName string, parameters CertificateCreateOrUpdateParameters, ifMatch string) (result Certificate, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}, + {Target: "accountName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}, + {TargetValue: certificateName, + Constraints: []validation.Constraint{{Target: "certificateName", Name: validation.MaxLength, Rule: 45, Chain: nil}, + {Target: "certificateName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "certificateName", Name: validation.Pattern, Rule: `^[\w]+-[\w]+$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("batch.CertificateClient", "Update", err.Error()) + } + + req, err := client.UpdatePreparer(ctx, resourceGroupName, accountName, certificateName, parameters, ifMatch) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.CertificateClient", "Update", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "batch.CertificateClient", "Update", resp, "Failure sending request") + return + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.CertificateClient", "Update", resp, "Failure responding to request") + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client CertificateClient) UpdatePreparer(ctx context.Context, resourceGroupName string, accountName string, certificateName string, parameters CertificateCreateOrUpdateParameters, ifMatch string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "certificateName": autorest.Encode("path", certificateName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/certificates/{certificateName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + if len(ifMatch) > 0 { + preparer = autorest.DecoratePreparer(preparer, + autorest.WithHeader("If-Match", autorest.String(ifMatch))) + } + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// UpdateSender sends the Update request. The method will close the +// http.Response Body if it receives an error. +func (client CertificateClient) UpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client CertificateClient) UpdateResponder(resp *http.Response) (result Certificate, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/client.go b/vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/client.go new file mode 100644 index 000000000000..0b2df1e39a3e --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/client.go @@ -0,0 +1,51 @@ +// Package batch implements the Azure ARM Batch service API version 2017-09-01. +// +// +package batch + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" +) + +const ( + // DefaultBaseURI is the default URI used for the service Batch + DefaultBaseURI = "https://management.azure.com" +) + +// BaseClient is the base client for Batch. +type BaseClient struct { + autorest.Client + BaseURI string + SubscriptionID string +} + +// New creates an instance of the BaseClient client. +func New(subscriptionID string) BaseClient { + return NewWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewWithBaseURI creates an instance of the BaseClient client. +func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient { + return BaseClient{ + Client: autorest.NewClientWithUserAgent(UserAgent()), + BaseURI: baseURI, + SubscriptionID: subscriptionID, + } +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/location.go b/vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/location.go new file mode 100644 index 000000000000..6e0b0c64411e --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/location.go @@ -0,0 +1,181 @@ +package batch + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// LocationClient is the client for the Location methods of the Batch service. +type LocationClient struct { + BaseClient +} + +// NewLocationClient creates an instance of the LocationClient client. +func NewLocationClient(subscriptionID string) LocationClient { + return NewLocationClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewLocationClientWithBaseURI creates an instance of the LocationClient client. +func NewLocationClientWithBaseURI(baseURI string, subscriptionID string) LocationClient { + return LocationClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CheckNameAvailability checks whether the Batch account name is available in the specified region. +// Parameters: +// locationName - the desired region for the name check. +// parameters - properties needed to check the availability of a name. +func (client LocationClient) CheckNameAvailability(ctx context.Context, locationName string, parameters CheckNameAvailabilityParameters) (result CheckNameAvailabilityResult, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.Name", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.Type", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("batch.LocationClient", "CheckNameAvailability", err.Error()) + } + + req, err := client.CheckNameAvailabilityPreparer(ctx, locationName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.LocationClient", "CheckNameAvailability", nil, "Failure preparing request") + return + } + + resp, err := client.CheckNameAvailabilitySender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "batch.LocationClient", "CheckNameAvailability", resp, "Failure sending request") + return + } + + result, err = client.CheckNameAvailabilityResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.LocationClient", "CheckNameAvailability", resp, "Failure responding to request") + } + + return +} + +// CheckNameAvailabilityPreparer prepares the CheckNameAvailability request. +func (client LocationClient) CheckNameAvailabilityPreparer(ctx context.Context, locationName string, parameters CheckNameAvailabilityParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "locationName": autorest.Encode("path", locationName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/checkNameAvailability", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CheckNameAvailabilitySender sends the CheckNameAvailability request. The method will close the +// http.Response Body if it receives an error. +func (client LocationClient) CheckNameAvailabilitySender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CheckNameAvailabilityResponder handles the response to the CheckNameAvailability request. The method always +// closes the http.Response Body. +func (client LocationClient) CheckNameAvailabilityResponder(resp *http.Response) (result CheckNameAvailabilityResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetQuotas gets the Batch service quotas for the specified subscription at the given location. +// Parameters: +// locationName - the region for which to retrieve Batch service quotas. +func (client LocationClient) GetQuotas(ctx context.Context, locationName string) (result LocationQuota, err error) { + req, err := client.GetQuotasPreparer(ctx, locationName) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.LocationClient", "GetQuotas", nil, "Failure preparing request") + return + } + + resp, err := client.GetQuotasSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "batch.LocationClient", "GetQuotas", resp, "Failure sending request") + return + } + + result, err = client.GetQuotasResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.LocationClient", "GetQuotas", resp, "Failure responding to request") + } + + return +} + +// GetQuotasPreparer prepares the GetQuotas request. +func (client LocationClient) GetQuotasPreparer(ctx context.Context, locationName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "locationName": autorest.Encode("path", locationName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/quotas", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetQuotasSender sends the GetQuotas request. The method will close the +// http.Response Body if it receives an error. +func (client LocationClient) GetQuotasSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetQuotasResponder handles the response to the GetQuotas request. The method always +// closes the http.Response Body. +func (client LocationClient) GetQuotasResponder(resp *http.Response) (result LocationQuota, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/models.go new file mode 100644 index 000000000000..b55c52c590d4 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/models.go @@ -0,0 +1,2152 @@ +package batch + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "encoding/json" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/date" + "github.com/Azure/go-autorest/autorest/to" + "net/http" +) + +// AccountKeyType enumerates the values for account key type. +type AccountKeyType string + +const ( + // Primary ... + Primary AccountKeyType = "Primary" + // Secondary ... + Secondary AccountKeyType = "Secondary" +) + +// PossibleAccountKeyTypeValues returns an array of possible values for the AccountKeyType const type. +func PossibleAccountKeyTypeValues() []AccountKeyType { + return []AccountKeyType{Primary, Secondary} +} + +// AllocationState enumerates the values for allocation state. +type AllocationState string + +const ( + // Resizing ... + Resizing AllocationState = "Resizing" + // Steady ... + Steady AllocationState = "Steady" + // Stopping ... + Stopping AllocationState = "Stopping" +) + +// PossibleAllocationStateValues returns an array of possible values for the AllocationState const type. +func PossibleAllocationStateValues() []AllocationState { + return []AllocationState{Resizing, Steady, Stopping} +} + +// AutoUserScope enumerates the values for auto user scope. +type AutoUserScope string + +const ( + // AutoUserScopePool ... + AutoUserScopePool AutoUserScope = "Pool" + // AutoUserScopeTask ... + AutoUserScopeTask AutoUserScope = "Task" +) + +// PossibleAutoUserScopeValues returns an array of possible values for the AutoUserScope const type. +func PossibleAutoUserScopeValues() []AutoUserScope { + return []AutoUserScope{AutoUserScopePool, AutoUserScopeTask} +} + +// CachingType enumerates the values for caching type. +type CachingType string + +const ( + // None ... + None CachingType = "None" + // ReadOnly ... + ReadOnly CachingType = "ReadOnly" + // ReadWrite ... + ReadWrite CachingType = "ReadWrite" +) + +// PossibleCachingTypeValues returns an array of possible values for the CachingType const type. +func PossibleCachingTypeValues() []CachingType { + return []CachingType{None, ReadOnly, ReadWrite} +} + +// CertificateFormat enumerates the values for certificate format. +type CertificateFormat string + +const ( + // Cer ... + Cer CertificateFormat = "Cer" + // Pfx ... + Pfx CertificateFormat = "Pfx" +) + +// PossibleCertificateFormatValues returns an array of possible values for the CertificateFormat const type. +func PossibleCertificateFormatValues() []CertificateFormat { + return []CertificateFormat{Cer, Pfx} +} + +// CertificateProvisioningState enumerates the values for certificate provisioning state. +type CertificateProvisioningState string + +const ( + // Deleting ... + Deleting CertificateProvisioningState = "Deleting" + // Failed ... + Failed CertificateProvisioningState = "Failed" + // Succeeded ... + Succeeded CertificateProvisioningState = "Succeeded" +) + +// PossibleCertificateProvisioningStateValues returns an array of possible values for the CertificateProvisioningState const type. +func PossibleCertificateProvisioningStateValues() []CertificateProvisioningState { + return []CertificateProvisioningState{Deleting, Failed, Succeeded} +} + +// CertificateStoreLocation enumerates the values for certificate store location. +type CertificateStoreLocation string + +const ( + // CurrentUser ... + CurrentUser CertificateStoreLocation = "CurrentUser" + // LocalMachine ... + LocalMachine CertificateStoreLocation = "LocalMachine" +) + +// PossibleCertificateStoreLocationValues returns an array of possible values for the CertificateStoreLocation const type. +func PossibleCertificateStoreLocationValues() []CertificateStoreLocation { + return []CertificateStoreLocation{CurrentUser, LocalMachine} +} + +// CertificateVisibility enumerates the values for certificate visibility. +type CertificateVisibility string + +const ( + // CertificateVisibilityRemoteUser ... + CertificateVisibilityRemoteUser CertificateVisibility = "RemoteUser" + // CertificateVisibilityStartTask ... + CertificateVisibilityStartTask CertificateVisibility = "StartTask" + // CertificateVisibilityTask ... + CertificateVisibilityTask CertificateVisibility = "Task" +) + +// PossibleCertificateVisibilityValues returns an array of possible values for the CertificateVisibility const type. +func PossibleCertificateVisibilityValues() []CertificateVisibility { + return []CertificateVisibility{CertificateVisibilityRemoteUser, CertificateVisibilityStartTask, CertificateVisibilityTask} +} + +// ComputeNodeDeallocationOption enumerates the values for compute node deallocation option. +type ComputeNodeDeallocationOption string + +const ( + // Requeue ... + Requeue ComputeNodeDeallocationOption = "Requeue" + // RetainedData ... + RetainedData ComputeNodeDeallocationOption = "RetainedData" + // TaskCompletion ... + TaskCompletion ComputeNodeDeallocationOption = "TaskCompletion" + // Terminate ... + Terminate ComputeNodeDeallocationOption = "Terminate" +) + +// PossibleComputeNodeDeallocationOptionValues returns an array of possible values for the ComputeNodeDeallocationOption const type. +func PossibleComputeNodeDeallocationOptionValues() []ComputeNodeDeallocationOption { + return []ComputeNodeDeallocationOption{Requeue, RetainedData, TaskCompletion, Terminate} +} + +// ComputeNodeFillType enumerates the values for compute node fill type. +type ComputeNodeFillType string + +const ( + // Pack ... + Pack ComputeNodeFillType = "Pack" + // Spread ... + Spread ComputeNodeFillType = "Spread" +) + +// PossibleComputeNodeFillTypeValues returns an array of possible values for the ComputeNodeFillType const type. +func PossibleComputeNodeFillTypeValues() []ComputeNodeFillType { + return []ComputeNodeFillType{Pack, Spread} +} + +// ElevationLevel enumerates the values for elevation level. +type ElevationLevel string + +const ( + // Admin ... + Admin ElevationLevel = "Admin" + // NonAdmin ... + NonAdmin ElevationLevel = "NonAdmin" +) + +// PossibleElevationLevelValues returns an array of possible values for the ElevationLevel const type. +func PossibleElevationLevelValues() []ElevationLevel { + return []ElevationLevel{Admin, NonAdmin} +} + +// InboundEndpointProtocol enumerates the values for inbound endpoint protocol. +type InboundEndpointProtocol string + +const ( + // TCP ... + TCP InboundEndpointProtocol = "TCP" + // UDP ... + UDP InboundEndpointProtocol = "UDP" +) + +// PossibleInboundEndpointProtocolValues returns an array of possible values for the InboundEndpointProtocol const type. +func PossibleInboundEndpointProtocolValues() []InboundEndpointProtocol { + return []InboundEndpointProtocol{TCP, UDP} +} + +// InterNodeCommunicationState enumerates the values for inter node communication state. +type InterNodeCommunicationState string + +const ( + // Disabled ... + Disabled InterNodeCommunicationState = "Disabled" + // Enabled ... + Enabled InterNodeCommunicationState = "Enabled" +) + +// PossibleInterNodeCommunicationStateValues returns an array of possible values for the InterNodeCommunicationState const type. +func PossibleInterNodeCommunicationStateValues() []InterNodeCommunicationState { + return []InterNodeCommunicationState{Disabled, Enabled} +} + +// NameAvailabilityReason enumerates the values for name availability reason. +type NameAvailabilityReason string + +const ( + // AlreadyExists ... + AlreadyExists NameAvailabilityReason = "AlreadyExists" + // Invalid ... + Invalid NameAvailabilityReason = "Invalid" +) + +// PossibleNameAvailabilityReasonValues returns an array of possible values for the NameAvailabilityReason const type. +func PossibleNameAvailabilityReasonValues() []NameAvailabilityReason { + return []NameAvailabilityReason{AlreadyExists, Invalid} +} + +// NetworkSecurityGroupRuleAccess enumerates the values for network security group rule access. +type NetworkSecurityGroupRuleAccess string + +const ( + // Allow ... + Allow NetworkSecurityGroupRuleAccess = "Allow" + // Deny ... + Deny NetworkSecurityGroupRuleAccess = "Deny" +) + +// PossibleNetworkSecurityGroupRuleAccessValues returns an array of possible values for the NetworkSecurityGroupRuleAccess const type. +func PossibleNetworkSecurityGroupRuleAccessValues() []NetworkSecurityGroupRuleAccess { + return []NetworkSecurityGroupRuleAccess{Allow, Deny} +} + +// PackageState enumerates the values for package state. +type PackageState string + +const ( + // Active ... + Active PackageState = "Active" + // Pending ... + Pending PackageState = "Pending" + // Unmapped ... + Unmapped PackageState = "Unmapped" +) + +// PossiblePackageStateValues returns an array of possible values for the PackageState const type. +func PossiblePackageStateValues() []PackageState { + return []PackageState{Active, Pending, Unmapped} +} + +// PoolAllocationMode enumerates the values for pool allocation mode. +type PoolAllocationMode string + +const ( + // BatchService ... + BatchService PoolAllocationMode = "BatchService" + // UserSubscription ... + UserSubscription PoolAllocationMode = "UserSubscription" +) + +// PossiblePoolAllocationModeValues returns an array of possible values for the PoolAllocationMode const type. +func PossiblePoolAllocationModeValues() []PoolAllocationMode { + return []PoolAllocationMode{BatchService, UserSubscription} +} + +// PoolProvisioningState enumerates the values for pool provisioning state. +type PoolProvisioningState string + +const ( + // PoolProvisioningStateDeleting ... + PoolProvisioningStateDeleting PoolProvisioningState = "Deleting" + // PoolProvisioningStateSucceeded ... + PoolProvisioningStateSucceeded PoolProvisioningState = "Succeeded" +) + +// PossiblePoolProvisioningStateValues returns an array of possible values for the PoolProvisioningState const type. +func PossiblePoolProvisioningStateValues() []PoolProvisioningState { + return []PoolProvisioningState{PoolProvisioningStateDeleting, PoolProvisioningStateSucceeded} +} + +// ProvisioningState enumerates the values for provisioning state. +type ProvisioningState string + +const ( + // ProvisioningStateCancelled ... + ProvisioningStateCancelled ProvisioningState = "Cancelled" + // ProvisioningStateCreating ... + ProvisioningStateCreating ProvisioningState = "Creating" + // ProvisioningStateDeleting ... + ProvisioningStateDeleting ProvisioningState = "Deleting" + // ProvisioningStateFailed ... + ProvisioningStateFailed ProvisioningState = "Failed" + // ProvisioningStateInvalid ... + ProvisioningStateInvalid ProvisioningState = "Invalid" + // ProvisioningStateSucceeded ... + ProvisioningStateSucceeded ProvisioningState = "Succeeded" +) + +// PossibleProvisioningStateValues returns an array of possible values for the ProvisioningState const type. +func PossibleProvisioningStateValues() []ProvisioningState { + return []ProvisioningState{ProvisioningStateCancelled, ProvisioningStateCreating, ProvisioningStateDeleting, ProvisioningStateFailed, ProvisioningStateInvalid, ProvisioningStateSucceeded} +} + +// StorageAccountType enumerates the values for storage account type. +type StorageAccountType string + +const ( + // PremiumLRS ... + PremiumLRS StorageAccountType = "Premium_LRS" + // StandardLRS ... + StandardLRS StorageAccountType = "Standard_LRS" +) + +// PossibleStorageAccountTypeValues returns an array of possible values for the StorageAccountType const type. +func PossibleStorageAccountTypeValues() []StorageAccountType { + return []StorageAccountType{PremiumLRS, StandardLRS} +} + +// Account contains information about an Azure Batch account. +type Account struct { + autorest.Response `json:"-"` + // AccountProperties - The properties associated with the account. + *AccountProperties `json:"properties,omitempty"` + // ID - The ID of the resource. + ID *string `json:"id,omitempty"` + // Name - The name of the resource. + Name *string `json:"name,omitempty"` + // Type - The type of the resource. + Type *string `json:"type,omitempty"` + // Location - The location of the resource. + Location *string `json:"location,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for Account. +func (a Account) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if a.AccountProperties != nil { + objectMap["properties"] = a.AccountProperties + } + if a.ID != nil { + objectMap["id"] = a.ID + } + if a.Name != nil { + objectMap["name"] = a.Name + } + if a.Type != nil { + objectMap["type"] = a.Type + } + if a.Location != nil { + objectMap["location"] = a.Location + } + if a.Tags != nil { + objectMap["tags"] = a.Tags + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for Account struct. +func (a *Account) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var accountProperties AccountProperties + err = json.Unmarshal(*v, &accountProperties) + if err != nil { + return err + } + a.AccountProperties = &accountProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + a.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + a.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + a.Type = &typeVar + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + a.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + a.Tags = tags + } + } + } + + return nil +} + +// AccountCreateFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type AccountCreateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *AccountCreateFuture) Result(client AccountClient) (a Account, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.AccountCreateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("batch.AccountCreateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if a.Response.Response, err = future.GetResult(sender); err == nil && a.Response.Response.StatusCode != http.StatusNoContent { + a, err = client.CreateResponder(a.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.AccountCreateFuture", "Result", a.Response.Response, "Failure responding to request") + } + } + return +} + +// AccountCreateParameters parameters supplied to the Create operation. +type AccountCreateParameters struct { + // Location - The region in which to create the account. + Location *string `json:"location,omitempty"` + // Tags - The user-specified tags associated with the account. + Tags map[string]*string `json:"tags"` + // AccountCreateProperties - The properties of the Batch account. + *AccountCreateProperties `json:"properties,omitempty"` +} + +// MarshalJSON is the custom marshaler for AccountCreateParameters. +func (acp AccountCreateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if acp.Location != nil { + objectMap["location"] = acp.Location + } + if acp.Tags != nil { + objectMap["tags"] = acp.Tags + } + if acp.AccountCreateProperties != nil { + objectMap["properties"] = acp.AccountCreateProperties + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for AccountCreateParameters struct. +func (acp *AccountCreateParameters) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + acp.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + acp.Tags = tags + } + case "properties": + if v != nil { + var accountCreateProperties AccountCreateProperties + err = json.Unmarshal(*v, &accountCreateProperties) + if err != nil { + return err + } + acp.AccountCreateProperties = &accountCreateProperties + } + } + } + + return nil +} + +// AccountCreateProperties the properties of a Batch account. +type AccountCreateProperties struct { + // AutoStorage - The properties related to the auto-storage account. + AutoStorage *AutoStorageBaseProperties `json:"autoStorage,omitempty"` + // PoolAllocationMode - The pool allocation mode also affects how clients may authenticate to the Batch Service API. If the mode is BatchService, clients may authenticate using access keys or Azure Active Directory. If the mode is UserSubscription, clients must use Azure Active Directory. The default is BatchService. Possible values include: 'BatchService', 'UserSubscription' + PoolAllocationMode PoolAllocationMode `json:"poolAllocationMode,omitempty"` + // KeyVaultReference - A reference to the Azure key vault associated with the Batch account. + KeyVaultReference *KeyVaultReference `json:"keyVaultReference,omitempty"` +} + +// AccountDeleteFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type AccountDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *AccountDeleteFuture) Result(client AccountClient) (ar autorest.Response, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.AccountDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("batch.AccountDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// AccountKeys a set of Azure Batch account keys. +type AccountKeys struct { + autorest.Response `json:"-"` + // AccountName - The Batch account name. + AccountName *string `json:"accountName,omitempty"` + // Primary - The primary key associated with the account. + Primary *string `json:"primary,omitempty"` + // Secondary - The secondary key associated with the account. + Secondary *string `json:"secondary,omitempty"` +} + +// AccountListResult values returned by the List operation. +type AccountListResult struct { + autorest.Response `json:"-"` + // Value - The collection of Batch accounts returned by the listing operation. + Value *[]Account `json:"value,omitempty"` + // NextLink - The continuation token. + NextLink *string `json:"nextLink,omitempty"` +} + +// AccountListResultIterator provides access to a complete listing of Account values. +type AccountListResultIterator struct { + i int + page AccountListResultPage +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *AccountListResultIterator) Next() error { + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err := iter.page.Next() + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter AccountListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter AccountListResultIterator) Response() AccountListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter AccountListResultIterator) Value() Account { + if !iter.page.NotDone() { + return Account{} + } + return iter.page.Values()[iter.i] +} + +// IsEmpty returns true if the ListResult contains no values. +func (alr AccountListResult) IsEmpty() bool { + return alr.Value == nil || len(*alr.Value) == 0 +} + +// accountListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (alr AccountListResult) accountListResultPreparer() (*http.Request, error) { + if alr.NextLink == nil || len(to.String(alr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(alr.NextLink))) +} + +// AccountListResultPage contains a page of Account values. +type AccountListResultPage struct { + fn func(AccountListResult) (AccountListResult, error) + alr AccountListResult +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *AccountListResultPage) Next() error { + next, err := page.fn(page.alr) + if err != nil { + return err + } + page.alr = next + return nil +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page AccountListResultPage) NotDone() bool { + return !page.alr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page AccountListResultPage) Response() AccountListResult { + return page.alr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page AccountListResultPage) Values() []Account { + if page.alr.IsEmpty() { + return nil + } + return *page.alr.Value +} + +// AccountProperties account specific properties. +type AccountProperties struct { + // AccountEndpoint - The account endpoint used to interact with the Batch service. + AccountEndpoint *string `json:"accountEndpoint,omitempty"` + // ProvisioningState - The provisioned state of the resource. Possible values include: 'ProvisioningStateInvalid', 'ProvisioningStateCreating', 'ProvisioningStateDeleting', 'ProvisioningStateSucceeded', 'ProvisioningStateFailed', 'ProvisioningStateCancelled' + ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` + // PoolAllocationMode - Possible values include: 'BatchService', 'UserSubscription' + PoolAllocationMode PoolAllocationMode `json:"poolAllocationMode,omitempty"` + KeyVaultReference *KeyVaultReference `json:"keyVaultReference,omitempty"` + AutoStorage *AutoStorageProperties `json:"autoStorage,omitempty"` + DedicatedCoreQuota *int32 `json:"dedicatedCoreQuota,omitempty"` + LowPriorityCoreQuota *int32 `json:"lowPriorityCoreQuota,omitempty"` + PoolQuota *int32 `json:"poolQuota,omitempty"` + ActiveJobAndJobScheduleQuota *int32 `json:"activeJobAndJobScheduleQuota,omitempty"` +} + +// AccountRegenerateKeyParameters parameters supplied to the RegenerateKey operation. +type AccountRegenerateKeyParameters struct { + // KeyName - The type of account key to regenerate. Possible values include: 'Primary', 'Secondary' + KeyName AccountKeyType `json:"keyName,omitempty"` +} + +// AccountUpdateParameters parameters for updating an Azure Batch account. +type AccountUpdateParameters struct { + // Tags - The user-specified tags associated with the account. + Tags map[string]*string `json:"tags"` + // AccountUpdateProperties - The properties of the account. + *AccountUpdateProperties `json:"properties,omitempty"` +} + +// MarshalJSON is the custom marshaler for AccountUpdateParameters. +func (aup AccountUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if aup.Tags != nil { + objectMap["tags"] = aup.Tags + } + if aup.AccountUpdateProperties != nil { + objectMap["properties"] = aup.AccountUpdateProperties + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for AccountUpdateParameters struct. +func (aup *AccountUpdateParameters) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + aup.Tags = tags + } + case "properties": + if v != nil { + var accountUpdateProperties AccountUpdateProperties + err = json.Unmarshal(*v, &accountUpdateProperties) + if err != nil { + return err + } + aup.AccountUpdateProperties = &accountUpdateProperties + } + } + } + + return nil +} + +// AccountUpdateProperties the properties of a Batch account. +type AccountUpdateProperties struct { + // AutoStorage - The properties related to the auto-storage account. + AutoStorage *AutoStorageBaseProperties `json:"autoStorage,omitempty"` +} + +// ActivateApplicationPackageParameters parameters for an activating an application package. +type ActivateApplicationPackageParameters struct { + // Format - The format of the application package binary file. + Format *string `json:"format,omitempty"` +} + +// Application contains information about an application in a Batch account. +type Application struct { + autorest.Response `json:"-"` + // ID - A string that uniquely identifies the application within the account. + ID *string `json:"id,omitempty"` + // DisplayName - The display name for the application. + DisplayName *string `json:"displayName,omitempty"` + // Packages - The list of packages under this application. + Packages *[]ApplicationPackage `json:"packages,omitempty"` + // AllowUpdates - A value indicating whether packages within the application may be overwritten using the same version string. + AllowUpdates *bool `json:"allowUpdates,omitempty"` + // DefaultVersion - The package to use if a client requests the application but does not specify a version. + DefaultVersion *string `json:"defaultVersion,omitempty"` +} + +// ApplicationCreateParameters parameters for adding an Application. +type ApplicationCreateParameters struct { + // AllowUpdates - A value indicating whether packages within the application may be overwritten using the same version string. + AllowUpdates *bool `json:"allowUpdates,omitempty"` + // DisplayName - The display name for the application. + DisplayName *string `json:"displayName,omitempty"` +} + +// ApplicationPackage an application package which represents a particular version of an application. +type ApplicationPackage struct { + autorest.Response `json:"-"` + // ID - The ID of the application. + ID *string `json:"id,omitempty"` + // Version - The version of the application package. + Version *string `json:"version,omitempty"` + // State - The current state of the application package. Possible values include: 'Pending', 'Active', 'Unmapped' + State PackageState `json:"state,omitempty"` + // Format - The format of the application package, if the package is active. + Format *string `json:"format,omitempty"` + // StorageURL - The URL for the application package in Azure Storage. + StorageURL *string `json:"storageUrl,omitempty"` + // StorageURLExpiry - The UTC time at which the Azure Storage URL will expire. + StorageURLExpiry *date.Time `json:"storageUrlExpiry,omitempty"` + // LastActivationTime - The time at which the package was last activated, if the package is active. + LastActivationTime *date.Time `json:"lastActivationTime,omitempty"` +} + +// ApplicationPackageReference ... +type ApplicationPackageReference struct { + ID *string `json:"id,omitempty"` + // Version - If this is omitted, and no default version is specified for this application, the request fails with the error code InvalidApplicationPackageReferences. If you are calling the REST API directly, the HTTP status code is 409. + Version *string `json:"version,omitempty"` +} + +// ApplicationUpdateParameters parameters for an update application request. +type ApplicationUpdateParameters struct { + // AllowUpdates - A value indicating whether packages within the application may be overwritten using the same version string. + AllowUpdates *bool `json:"allowUpdates,omitempty"` + // DefaultVersion - The package to use if a client requests the application but does not specify a version. + DefaultVersion *string `json:"defaultVersion,omitempty"` + // DisplayName - The display name for the application. + DisplayName *string `json:"displayName,omitempty"` +} + +// AutoScaleRun ... +type AutoScaleRun struct { + EvaluationTime *date.Time `json:"evaluationTime,omitempty"` + // Results - Each variable value is returned in the form $variable=value, and variables are separated by semicolons. + Results *string `json:"results,omitempty"` + Error *AutoScaleRunError `json:"error,omitempty"` +} + +// AutoScaleRunError ... +type AutoScaleRunError struct { + // Code - An identifier for the error. Codes are invariant and are intended to be consumed programmatically. + Code *string `json:"code,omitempty"` + // Message - A message describing the error, intended to be suitable for display in a user interface. + Message *string `json:"message,omitempty"` + Details *[]AutoScaleRunError `json:"details,omitempty"` +} + +// AutoScaleSettings ... +type AutoScaleSettings struct { + Formula *string `json:"formula,omitempty"` + // EvaluationInterval - If omitted, the default value is 15 minutes (PT15M). + EvaluationInterval *string `json:"evaluationInterval,omitempty"` +} + +// AutoStorageBaseProperties the properties related to the auto-storage account. +type AutoStorageBaseProperties struct { + // StorageAccountID - The resource ID of the storage account to be used for auto-storage account. + StorageAccountID *string `json:"storageAccountId,omitempty"` +} + +// AutoStorageProperties contains information about the auto-storage account associated with a Batch account. +type AutoStorageProperties struct { + // LastKeySync - The UTC time at which storage keys were last synchronized with the Batch account. + LastKeySync *date.Time `json:"lastKeySync,omitempty"` + // StorageAccountID - The resource ID of the storage account to be used for auto-storage account. + StorageAccountID *string `json:"storageAccountId,omitempty"` +} + +// AutoUserSpecification ... +type AutoUserSpecification struct { + // Scope - pool - specifies that the task runs as the common auto user account which is created on every node in a pool. task - specifies that the service should create a new user for the task. The default value is task. Possible values include: 'AutoUserScopeTask', 'AutoUserScopePool' + Scope AutoUserScope `json:"scope,omitempty"` + // ElevationLevel - nonAdmin - The auto user is a standard user without elevated access. admin - The auto user is a user with elevated access and operates with full Administrator permissions. The default value is nonAdmin. Possible values include: 'NonAdmin', 'Admin' + ElevationLevel ElevationLevel `json:"elevationLevel,omitempty"` +} + +// Certificate contains information about a certificate. +type Certificate struct { + autorest.Response `json:"-"` + // CertificateProperties - The properties associated with the certificate. + *CertificateProperties `json:"properties,omitempty"` + // ID - The ID of the resource. + ID *string `json:"id,omitempty"` + // Name - The name of the resource. + Name *string `json:"name,omitempty"` + // Type - The type of the resource. + Type *string `json:"type,omitempty"` + // Etag - The ETag of the resource, used for concurrency statements. + Etag *string `json:"etag,omitempty"` +} + +// MarshalJSON is the custom marshaler for Certificate. +func (c Certificate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if c.CertificateProperties != nil { + objectMap["properties"] = c.CertificateProperties + } + if c.ID != nil { + objectMap["id"] = c.ID + } + if c.Name != nil { + objectMap["name"] = c.Name + } + if c.Type != nil { + objectMap["type"] = c.Type + } + if c.Etag != nil { + objectMap["etag"] = c.Etag + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for Certificate struct. +func (c *Certificate) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var certificateProperties CertificateProperties + err = json.Unmarshal(*v, &certificateProperties) + if err != nil { + return err + } + c.CertificateProperties = &certificateProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + c.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + c.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + c.Type = &typeVar + } + case "etag": + if v != nil { + var etag string + err = json.Unmarshal(*v, &etag) + if err != nil { + return err + } + c.Etag = &etag + } + } + } + + return nil +} + +// CertificateBaseProperties ... +type CertificateBaseProperties struct { + // ThumbprintAlgorithm - This must match the first portion of the certificate name. Currently required to be 'SHA1'. + ThumbprintAlgorithm *string `json:"thumbprintAlgorithm,omitempty"` + // Thumbprint - This must match the thumbprint from the name. + Thumbprint *string `json:"thumbprint,omitempty"` + // Format - The format of the certificate - either Pfx or Cer. If omitted, the default is Pfx. Possible values include: 'Pfx', 'Cer' + Format CertificateFormat `json:"format,omitempty"` +} + +// CertificateCreateFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type CertificateCreateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *CertificateCreateFuture) Result(client CertificateClient) (c Certificate, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.CertificateCreateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("batch.CertificateCreateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if c.Response.Response, err = future.GetResult(sender); err == nil && c.Response.Response.StatusCode != http.StatusNoContent { + c, err = client.CreateResponder(c.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.CertificateCreateFuture", "Result", c.Response.Response, "Failure responding to request") + } + } + return +} + +// CertificateCreateOrUpdateParameters contains information about a certificate. +type CertificateCreateOrUpdateParameters struct { + // CertificateCreateOrUpdateProperties - The properties associated with the certificate. + *CertificateCreateOrUpdateProperties `json:"properties,omitempty"` + // ID - The ID of the resource. + ID *string `json:"id,omitempty"` + // Name - The name of the resource. + Name *string `json:"name,omitempty"` + // Type - The type of the resource. + Type *string `json:"type,omitempty"` + // Etag - The ETag of the resource, used for concurrency statements. + Etag *string `json:"etag,omitempty"` +} + +// MarshalJSON is the custom marshaler for CertificateCreateOrUpdateParameters. +func (ccoup CertificateCreateOrUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if ccoup.CertificateCreateOrUpdateProperties != nil { + objectMap["properties"] = ccoup.CertificateCreateOrUpdateProperties + } + if ccoup.ID != nil { + objectMap["id"] = ccoup.ID + } + if ccoup.Name != nil { + objectMap["name"] = ccoup.Name + } + if ccoup.Type != nil { + objectMap["type"] = ccoup.Type + } + if ccoup.Etag != nil { + objectMap["etag"] = ccoup.Etag + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for CertificateCreateOrUpdateParameters struct. +func (ccoup *CertificateCreateOrUpdateParameters) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var certificateCreateOrUpdateProperties CertificateCreateOrUpdateProperties + err = json.Unmarshal(*v, &certificateCreateOrUpdateProperties) + if err != nil { + return err + } + ccoup.CertificateCreateOrUpdateProperties = &certificateCreateOrUpdateProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + ccoup.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + ccoup.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + ccoup.Type = &typeVar + } + case "etag": + if v != nil { + var etag string + err = json.Unmarshal(*v, &etag) + if err != nil { + return err + } + ccoup.Etag = &etag + } + } + } + + return nil +} + +// CertificateCreateOrUpdateProperties certificate properties for create operations +type CertificateCreateOrUpdateProperties struct { + // Data - The maximum size is 10KB. + Data *string `json:"data,omitempty"` + // Password - This is required if the certificate format is pfx and must be omitted if the certificate format is cer. + Password *string `json:"password,omitempty"` + // ThumbprintAlgorithm - This must match the first portion of the certificate name. Currently required to be 'SHA1'. + ThumbprintAlgorithm *string `json:"thumbprintAlgorithm,omitempty"` + // Thumbprint - This must match the thumbprint from the name. + Thumbprint *string `json:"thumbprint,omitempty"` + // Format - The format of the certificate - either Pfx or Cer. If omitted, the default is Pfx. Possible values include: 'Pfx', 'Cer' + Format CertificateFormat `json:"format,omitempty"` +} + +// CertificateDeleteFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type CertificateDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *CertificateDeleteFuture) Result(client CertificateClient) (ar autorest.Response, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.CertificateDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("batch.CertificateDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// CertificateProperties certificate properties. +type CertificateProperties struct { + // ProvisioningState - Values are: + // Succeeded - The certificate is available for use in pools. + // Deleting - The user has requested that the certificate be deleted, but the delete operation has not yet completed. You may not reference the certificate when creating or updating pools. + // Failed - The user requested that the certificate be deleted, but there are pools that still have references to the certificate, or it is still installed on one or more compute nodes. (The latter can occur if the certificate has been removed from the pool, but the node has not yet restarted. Nodes refresh their certificates only when they restart.) You may use the cancel certificate delete operation to cancel the delete, or the delete certificate operation to retry the delete. Possible values include: 'Succeeded', 'Deleting', 'Failed' + ProvisioningState CertificateProvisioningState `json:"provisioningState,omitempty"` + ProvisioningStateTransitionTime *date.Time `json:"provisioningStateTransitionTime,omitempty"` + // PreviousProvisioningState - The previous provisioned state of the resource. Possible values include: 'Succeeded', 'Deleting', 'Failed' + PreviousProvisioningState CertificateProvisioningState `json:"previousProvisioningState,omitempty"` + PreviousProvisioningStateTransitionTime *date.Time `json:"previousProvisioningStateTransitionTime,omitempty"` + // PublicData - The public key of the certificate. + PublicData *string `json:"publicData,omitempty"` + // DeleteCertificateError - This is only returned when the certificate provisioningState is 'Failed'. + DeleteCertificateError *DeleteCertificateError `json:"deleteCertificateError,omitempty"` + // ThumbprintAlgorithm - This must match the first portion of the certificate name. Currently required to be 'SHA1'. + ThumbprintAlgorithm *string `json:"thumbprintAlgorithm,omitempty"` + // Thumbprint - This must match the thumbprint from the name. + Thumbprint *string `json:"thumbprint,omitempty"` + // Format - The format of the certificate - either Pfx or Cer. If omitted, the default is Pfx. Possible values include: 'Pfx', 'Cer' + Format CertificateFormat `json:"format,omitempty"` +} + +// CertificateReference ... +type CertificateReference struct { + ID *string `json:"id,omitempty"` + // StoreLocation - The default value is currentUser. This property is applicable only for pools configured with Windows nodes (that is, created with cloudServiceConfiguration, or with virtualMachineConfiguration using a Windows image reference). For Linux compute nodes, the certificates are stored in a directory inside the task working directory and an environment variable AZ_BATCH_CERTIFICATES_DIR is supplied to the task to query for this location. For certificates with visibility of 'remoteUser', a 'certs' directory is created in the user's home directory (e.g., /home/{user-name}/certs) and certificates are placed in that directory. Possible values include: 'CurrentUser', 'LocalMachine' + StoreLocation CertificateStoreLocation `json:"storeLocation,omitempty"` + // StoreName - This property is applicable only for pools configured with Windows nodes (that is, created with cloudServiceConfiguration, or with virtualMachineConfiguration using a Windows image reference). Common store names include: My, Root, CA, Trust, Disallowed, TrustedPeople, TrustedPublisher, AuthRoot, AddressBook, but any custom store name can also be used. The default value is My. + StoreName *string `json:"storeName,omitempty"` + // Visibility - Values are: + // starttask - The user account under which the start task is run. + // task - The accounts under which job tasks are run. + // remoteuser - The accounts under which users remotely access the node. + // You can specify more than one visibility in this collection. The default is all accounts. + Visibility *[]CertificateVisibility `json:"visibility,omitempty"` +} + +// CheckNameAvailabilityParameters parameters for a check name availability request. +type CheckNameAvailabilityParameters struct { + // Name - The name to check for availability + Name *string `json:"name,omitempty"` + // Type - The resource type. Must be set to Microsoft.Batch/batchAccounts + Type *string `json:"type,omitempty"` +} + +// CheckNameAvailabilityResult the CheckNameAvailability operation response. +type CheckNameAvailabilityResult struct { + autorest.Response `json:"-"` + // NameAvailable - Gets a boolean value that indicates whether the name is available for you to use. If true, the name is available. If false, the name has already been taken or invalid and cannot be used. + NameAvailable *bool `json:"nameAvailable,omitempty"` + // Reason - Gets the reason that a Batch account name could not be used. The Reason element is only returned if NameAvailable is false. Possible values include: 'Invalid', 'AlreadyExists' + Reason NameAvailabilityReason `json:"reason,omitempty"` + // Message - Gets an error message explaining the Reason value in more detail. + Message *string `json:"message,omitempty"` +} + +// CloudError an error response from the Batch service. +type CloudError struct { + Error *CloudErrorBody `json:"error,omitempty"` +} + +// CloudErrorBody an error response from the Batch service. +type CloudErrorBody struct { + // Code - An identifier for the error. Codes are invariant and are intended to be consumed programmatically. + Code *string `json:"code,omitempty"` + // Message - A message describing the error, intended to be suitable for display in a user interface. + Message *string `json:"message,omitempty"` + // Target - The target of the particular error. For example, the name of the property in error. + Target *string `json:"target,omitempty"` + // Details - A list of additional details about the error. + Details *[]CloudErrorBody `json:"details,omitempty"` +} + +// CloudServiceConfiguration ... +type CloudServiceConfiguration struct { + // OsFamily - Possible values are: 2 - OS Family 2, equivalent to Windows Server 2008 R2 SP1. 3 - OS Family 3, equivalent to Windows Server 2012. 4 - OS Family 4, equivalent to Windows Server 2012 R2. 5 - OS Family 5, equivalent to Windows Server 2016. For more information, see Azure Guest OS Releases (https://azure.microsoft.com/documentation/articles/cloud-services-guestos-update-matrix/#releases). + OsFamily *string `json:"osFamily,omitempty"` + // TargetOSVersion - The default value is * which specifies the latest operating system version for the specified OS family. + TargetOSVersion *string `json:"targetOSVersion,omitempty"` + // CurrentOSVersion - This may differ from targetOSVersion if the pool state is Upgrading. In this case some virtual machines may be on the targetOSVersion and some may be on the currentOSVersion during the upgrade process. Once all virtual machines have upgraded, currentOSVersion is updated to be the same as targetOSVersion. + CurrentOSVersion *string `json:"currentOSVersion,omitempty"` +} + +// DataDisk data Disk settings which will be used by the data disks associated to Compute Nodes in the pool. +type DataDisk struct { + // Lun - The lun is used to uniquely identify each data disk. If attaching multiple disks, each should have a distinct lun. + Lun *int32 `json:"lun,omitempty"` + // Caching - Values are: + // none - The caching mode for the disk is not enabled. + // readOnly - The caching mode for the disk is read only. + // readWrite - The caching mode for the disk is read and write. + // The default value for caching is none. For information about the caching options see: https://blogs.msdn.microsoft.com/windowsazurestorage/2012/06/27/exploring-windows-azure-drives-disks-and-images/. Possible values include: 'None', 'ReadOnly', 'ReadWrite' + Caching CachingType `json:"caching,omitempty"` + DiskSizeGB *int32 `json:"diskSizeGB,omitempty"` + // StorageAccountType - If omitted, the default is "Standard_LRS". Values are: + // Standard_LRS - The data disk should use standard locally redundant storage. + // Premium_LRS - The data disk should use premium locally redundant storage. Possible values include: 'StandardLRS', 'PremiumLRS' + StorageAccountType StorageAccountType `json:"storageAccountType,omitempty"` +} + +// DeleteCertificateError an error response from the Batch service. +type DeleteCertificateError struct { + // Code - An identifier for the error. Codes are invariant and are intended to be consumed programmatically. + Code *string `json:"code,omitempty"` + // Message - A message describing the error, intended to be suitable for display in a user interface. + Message *string `json:"message,omitempty"` + // Target - The target of the particular error. For example, the name of the property in error. + Target *string `json:"target,omitempty"` + // Details - A list of additional details about the error. + Details *[]DeleteCertificateError `json:"details,omitempty"` +} + +// DeploymentConfiguration ... +type DeploymentConfiguration struct { + // CloudServiceConfiguration - This property and virtualMachineConfiguration are mutually exclusive and one of the properties must be specified. This property cannot be specified if the Batch account was created with its poolAllocationMode property set to 'UserSubscription'. + CloudServiceConfiguration *CloudServiceConfiguration `json:"cloudServiceConfiguration,omitempty"` + // VirtualMachineConfiguration - This property and cloudServiceConfiguration are mutually exclusive and one of the properties must be specified. + VirtualMachineConfiguration *VirtualMachineConfiguration `json:"virtualMachineConfiguration,omitempty"` +} + +// EnvironmentSetting ... +type EnvironmentSetting struct { + Name *string `json:"name,omitempty"` + Value *string `json:"value,omitempty"` +} + +// FixedScaleSettings ... +type FixedScaleSettings struct { + // ResizeTimeout - The default value is 15 minutes. Timeout values use ISO 8601 format. For example, use PT10M for 10 minutes. The minimum value is 5 minutes. If you specify a value less than 5 minutes, the Batch service rejects the request with an error; if you are calling the REST API directly, the HTTP status code is 400 (Bad Request). + ResizeTimeout *string `json:"resizeTimeout,omitempty"` + // TargetDedicatedNodes - At least one of targetDedicatedNodes, targetLowPriority nodes must be set. + TargetDedicatedNodes *int32 `json:"targetDedicatedNodes,omitempty"` + // TargetLowPriorityNodes - At least one of targetDedicatedNodes, targetLowPriority nodes must be set. + TargetLowPriorityNodes *int32 `json:"targetLowPriorityNodes,omitempty"` + // NodeDeallocationOption - If omitted, the default value is Requeue. Possible values include: 'Requeue', 'Terminate', 'TaskCompletion', 'RetainedData' + NodeDeallocationOption ComputeNodeDeallocationOption `json:"nodeDeallocationOption,omitempty"` +} + +// ImageReference ... +type ImageReference struct { + // Publisher - For example, Canonical or MicrosoftWindowsServer. + Publisher *string `json:"publisher,omitempty"` + // Offer - For example, UbuntuServer or WindowsServer. + Offer *string `json:"offer,omitempty"` + // Sku - For example, 14.04.0-LTS or 2012-R2-Datacenter. + Sku *string `json:"sku,omitempty"` + // Version - A value of 'latest' can be specified to select the latest version of an image. If omitted, the default is 'latest'. + Version *string `json:"version,omitempty"` + // ID - This property is mutually exclusive with other properties. The virtual machine image must be in the same region and subscription as the Azure Batch account. For information about the firewall settings for Batch node agent to communicate with Batch service see https://docs.microsoft.com/en-us/azure/batch/batch-api-basics#virtual-network-vnet-and-firewall-configuration . + ID *string `json:"id,omitempty"` +} + +// InboundNatPool ... +type InboundNatPool struct { + // Name - The name must be unique within a Batch pool, can contain letters, numbers, underscores, periods, and hyphens. Names must start with a letter or number, must end with a letter, number, or underscore, and cannot exceed 77 characters. If any invalid values are provided the request fails with HTTP status code 400. + Name *string `json:"name,omitempty"` + // Protocol - Possible values include: 'TCP', 'UDP' + Protocol InboundEndpointProtocol `json:"protocol,omitempty"` + // BackendPort - This must be unique within a Batch pool. Acceptable values are between 1 and 65535 except for 22, 3389, 29876 and 29877 as these are reserved. If any reserved values are provided the request fails with HTTP status code 400. + BackendPort *int32 `json:"backendPort,omitempty"` + // FrontendPortRangeStart - Acceptable values range between 1 and 65534 except ports from 50000 to 55000 which are reserved. All ranges within a pool must be distinct and cannot overlap. If any reserved or overlapping values are provided the request fails with HTTP status code 400. + FrontendPortRangeStart *int32 `json:"frontendPortRangeStart,omitempty"` + // FrontendPortRangeEnd - Acceptable values range between 1 and 65534 except ports from 50000 to 55000 which are reserved by the Batch service. All ranges within a pool must be distinct and cannot overlap. If any reserved or overlapping values are provided the request fails with HTTP status code 400. + FrontendPortRangeEnd *int32 `json:"frontendPortRangeEnd,omitempty"` + // NetworkSecurityGroupRules - The maximum number of rules that can be specified across all the endpoints on a Batch pool is 25. If no network security group rules are specified, a default rule will be created to allow inbound access to the specified backendPort. If the maximum number of network security group rules is exceeded the request fails with HTTP status code 400. + NetworkSecurityGroupRules *[]NetworkSecurityGroupRule `json:"networkSecurityGroupRules,omitempty"` +} + +// KeyVaultReference identifies the Azure key vault associated with a Batch account. +type KeyVaultReference struct { + // ID - The resource ID of the Azure key vault associated with the Batch account. + ID *string `json:"id,omitempty"` + // URL - The URL of the Azure key vault associated with the Batch account. + URL *string `json:"url,omitempty"` +} + +// LinuxUserConfiguration ... +type LinuxUserConfiguration struct { + // UID - The uid and gid properties must be specified together or not at all. If not specified the underlying operating system picks the uid. + UID *int32 `json:"uid,omitempty"` + // Gid - The uid and gid properties must be specified together or not at all. If not specified the underlying operating system picks the gid. + Gid *int32 `json:"gid,omitempty"` + // SSHPrivateKey - The private key must not be password protected. The private key is used to automatically configure asymmetric-key based authentication for SSH between nodes in a Linux pool when the pool's enableInterNodeCommunication property is true (it is ignored if enableInterNodeCommunication is false). It does this by placing the key pair into the user's .ssh directory. If not specified, password-less SSH is not configured between nodes (no modification of the user's .ssh directory is done). + SSHPrivateKey *string `json:"sshPrivateKey,omitempty"` +} + +// ListApplicationsResult the result of performing list applications. +type ListApplicationsResult struct { + autorest.Response `json:"-"` + // Value - The list of applications. + Value *[]Application `json:"value,omitempty"` + // NextLink - The URL to get the next set of results. + NextLink *string `json:"nextLink,omitempty"` +} + +// ListApplicationsResultIterator provides access to a complete listing of Application values. +type ListApplicationsResultIterator struct { + i int + page ListApplicationsResultPage +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *ListApplicationsResultIterator) Next() error { + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err := iter.page.Next() + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter ListApplicationsResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter ListApplicationsResultIterator) Response() ListApplicationsResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter ListApplicationsResultIterator) Value() Application { + if !iter.page.NotDone() { + return Application{} + } + return iter.page.Values()[iter.i] +} + +// IsEmpty returns true if the ListResult contains no values. +func (lar ListApplicationsResult) IsEmpty() bool { + return lar.Value == nil || len(*lar.Value) == 0 +} + +// listApplicationsResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (lar ListApplicationsResult) listApplicationsResultPreparer() (*http.Request, error) { + if lar.NextLink == nil || len(to.String(lar.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(lar.NextLink))) +} + +// ListApplicationsResultPage contains a page of Application values. +type ListApplicationsResultPage struct { + fn func(ListApplicationsResult) (ListApplicationsResult, error) + lar ListApplicationsResult +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *ListApplicationsResultPage) Next() error { + next, err := page.fn(page.lar) + if err != nil { + return err + } + page.lar = next + return nil +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page ListApplicationsResultPage) NotDone() bool { + return !page.lar.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page ListApplicationsResultPage) Response() ListApplicationsResult { + return page.lar +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page ListApplicationsResultPage) Values() []Application { + if page.lar.IsEmpty() { + return nil + } + return *page.lar.Value +} + +// ListCertificatesResult values returned by the List operation. +type ListCertificatesResult struct { + autorest.Response `json:"-"` + // Value - The collection of returned certificates. + Value *[]Certificate `json:"value,omitempty"` + // NextLink - The continuation token. + NextLink *string `json:"nextLink,omitempty"` +} + +// ListCertificatesResultIterator provides access to a complete listing of Certificate values. +type ListCertificatesResultIterator struct { + i int + page ListCertificatesResultPage +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *ListCertificatesResultIterator) Next() error { + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err := iter.page.Next() + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter ListCertificatesResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter ListCertificatesResultIterator) Response() ListCertificatesResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter ListCertificatesResultIterator) Value() Certificate { + if !iter.page.NotDone() { + return Certificate{} + } + return iter.page.Values()[iter.i] +} + +// IsEmpty returns true if the ListResult contains no values. +func (lcr ListCertificatesResult) IsEmpty() bool { + return lcr.Value == nil || len(*lcr.Value) == 0 +} + +// listCertificatesResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (lcr ListCertificatesResult) listCertificatesResultPreparer() (*http.Request, error) { + if lcr.NextLink == nil || len(to.String(lcr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(lcr.NextLink))) +} + +// ListCertificatesResultPage contains a page of Certificate values. +type ListCertificatesResultPage struct { + fn func(ListCertificatesResult) (ListCertificatesResult, error) + lcr ListCertificatesResult +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *ListCertificatesResultPage) Next() error { + next, err := page.fn(page.lcr) + if err != nil { + return err + } + page.lcr = next + return nil +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page ListCertificatesResultPage) NotDone() bool { + return !page.lcr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page ListCertificatesResultPage) Response() ListCertificatesResult { + return page.lcr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page ListCertificatesResultPage) Values() []Certificate { + if page.lcr.IsEmpty() { + return nil + } + return *page.lcr.Value +} + +// ListPoolsResult values returned by the List operation. +type ListPoolsResult struct { + autorest.Response `json:"-"` + // Value - The collection of returned pools. + Value *[]Pool `json:"value,omitempty"` + // NextLink - The continuation token. + NextLink *string `json:"nextLink,omitempty"` +} + +// ListPoolsResultIterator provides access to a complete listing of Pool values. +type ListPoolsResultIterator struct { + i int + page ListPoolsResultPage +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *ListPoolsResultIterator) Next() error { + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err := iter.page.Next() + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter ListPoolsResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter ListPoolsResultIterator) Response() ListPoolsResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter ListPoolsResultIterator) Value() Pool { + if !iter.page.NotDone() { + return Pool{} + } + return iter.page.Values()[iter.i] +} + +// IsEmpty returns true if the ListResult contains no values. +func (lpr ListPoolsResult) IsEmpty() bool { + return lpr.Value == nil || len(*lpr.Value) == 0 +} + +// listPoolsResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (lpr ListPoolsResult) listPoolsResultPreparer() (*http.Request, error) { + if lpr.NextLink == nil || len(to.String(lpr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(lpr.NextLink))) +} + +// ListPoolsResultPage contains a page of Pool values. +type ListPoolsResultPage struct { + fn func(ListPoolsResult) (ListPoolsResult, error) + lpr ListPoolsResult +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *ListPoolsResultPage) Next() error { + next, err := page.fn(page.lpr) + if err != nil { + return err + } + page.lpr = next + return nil +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page ListPoolsResultPage) NotDone() bool { + return !page.lpr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page ListPoolsResultPage) Response() ListPoolsResult { + return page.lpr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page ListPoolsResultPage) Values() []Pool { + if page.lpr.IsEmpty() { + return nil + } + return *page.lpr.Value +} + +// LocationQuota quotas associated with a Batch region for a particular subscription. +type LocationQuota struct { + autorest.Response `json:"-"` + // AccountQuota - The number of Batch accounts that may be created under the subscription in the specified region. + AccountQuota *int32 `json:"accountQuota,omitempty"` +} + +// MetadataItem the Batch service does not assign any meaning to this metadata; it is solely for the use of user +// code. +type MetadataItem struct { + Name *string `json:"name,omitempty"` + Value *string `json:"value,omitempty"` +} + +// NetworkConfiguration the network configuration for a pool. +type NetworkConfiguration struct { + // SubnetID - The virtual network must be in the same region and subscription as the Azure Batch account. The specified subnet should have enough free IP addresses to accommodate the number of nodes in the pool. If the subnet doesn't have enough free IP addresses, the pool will partially allocate compute nodes, and a resize error will occur. The 'MicrosoftAzureBatch' service principal must have the 'Classic Virtual Machine Contributor' Role-Based Access Control (RBAC) role for the specified VNet. The specified subnet must allow communication from the Azure Batch service to be able to schedule tasks on the compute nodes. This can be verified by checking if the specified VNet has any associated Network Security Groups (NSG). If communication to the compute nodes in the specified subnet is denied by an NSG, then the Batch service will set the state of the compute nodes to unusable. For pools created via virtualMachineConfiguration the Batch account must have poolAllocationMode userSubscription in order to use a VNet. If the specified VNet has any associated Network Security Groups (NSG), then a few reserved system ports must be enabled for inbound communication. For pools created with a virtual machine configuration, enable ports 29876 and 29877, as well as port 22 for Linux and port 3389 for Windows. For pools created with a cloud service configuration, enable ports 10100, 20100, and 30100. Also enable outbound connections to Azure Storage on port 443. For more details see: https://docs.microsoft.com/en-us/azure/batch/batch-api-basics#virtual-network-vnet-and-firewall-configuration + SubnetID *string `json:"subnetId,omitempty"` + // EndpointConfiguration - Pool endpoint configuration is only supported on pools with the virtualMachineConfiguration property. + EndpointConfiguration *PoolEndpointConfiguration `json:"endpointConfiguration,omitempty"` +} + +// NetworkSecurityGroupRule ... +type NetworkSecurityGroupRule struct { + // Priority - Priorities within a pool must be unique and are evaluated in order of priority. The lower the number the higher the priority. For example, rules could be specified with order numbers of 150, 250, and 350. The rule with the order number of 150 takes precedence over the rule that has an order of 250. Allowed priorities are 150 to 3500. If any reserved or duplicate values are provided the request fails with HTTP status code 400. + Priority *int32 `json:"priority,omitempty"` + // Access - Possible values include: 'Allow', 'Deny' + Access NetworkSecurityGroupRuleAccess `json:"access,omitempty"` + // SourceAddressPrefix - Valid values are a single IP address (i.e. 10.10.10.10), IP subnet (i.e. 192.168.1.0/24), default tag, or * (for all addresses). If any other values are provided the request fails with HTTP status code 400. + SourceAddressPrefix *string `json:"sourceAddressPrefix,omitempty"` +} + +// Operation ... +type Operation struct { + // Name - This is of the format {provider}/{resource}/{operation} + Name *string `json:"name,omitempty"` + Display *OperationDisplay `json:"display,omitempty"` + Origin *string `json:"origin,omitempty"` + Properties interface{} `json:"properties,omitempty"` +} + +// OperationDisplay ... +type OperationDisplay struct { + Provider *string `json:"provider,omitempty"` + // Operation - For example: read, write, delete, or listKeys/action + Operation *string `json:"operation,omitempty"` + Resource *string `json:"resource,omitempty"` + Description *string `json:"description,omitempty"` +} + +// OperationListResult ... +type OperationListResult struct { + autorest.Response `json:"-"` + Value *[]Operation `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// OperationListResultIterator provides access to a complete listing of Operation values. +type OperationListResultIterator struct { + i int + page OperationListResultPage +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *OperationListResultIterator) Next() error { + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err := iter.page.Next() + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter OperationListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter OperationListResultIterator) Response() OperationListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter OperationListResultIterator) Value() Operation { + if !iter.page.NotDone() { + return Operation{} + } + return iter.page.Values()[iter.i] +} + +// IsEmpty returns true if the ListResult contains no values. +func (olr OperationListResult) IsEmpty() bool { + return olr.Value == nil || len(*olr.Value) == 0 +} + +// operationListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (olr OperationListResult) operationListResultPreparer() (*http.Request, error) { + if olr.NextLink == nil || len(to.String(olr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(olr.NextLink))) +} + +// OperationListResultPage contains a page of Operation values. +type OperationListResultPage struct { + fn func(OperationListResult) (OperationListResult, error) + olr OperationListResult +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *OperationListResultPage) Next() error { + next, err := page.fn(page.olr) + if err != nil { + return err + } + page.olr = next + return nil +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page OperationListResultPage) NotDone() bool { + return !page.olr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page OperationListResultPage) Response() OperationListResult { + return page.olr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page OperationListResultPage) Values() []Operation { + if page.olr.IsEmpty() { + return nil + } + return *page.olr.Value +} + +// OSDisk ... +type OSDisk struct { + // Caching - Default value is none. Possible values include: 'None', 'ReadOnly', 'ReadWrite' + Caching CachingType `json:"caching,omitempty"` +} + +// Pool contains information about a pool. +type Pool struct { + autorest.Response `json:"-"` + // PoolProperties - The properties associated with the pool. + *PoolProperties `json:"properties,omitempty"` + // ID - The ID of the resource. + ID *string `json:"id,omitempty"` + // Name - The name of the resource. + Name *string `json:"name,omitempty"` + // Type - The type of the resource. + Type *string `json:"type,omitempty"` + // Etag - The ETag of the resource, used for concurrency statements. + Etag *string `json:"etag,omitempty"` +} + +// MarshalJSON is the custom marshaler for Pool. +func (p Pool) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if p.PoolProperties != nil { + objectMap["properties"] = p.PoolProperties + } + if p.ID != nil { + objectMap["id"] = p.ID + } + if p.Name != nil { + objectMap["name"] = p.Name + } + if p.Type != nil { + objectMap["type"] = p.Type + } + if p.Etag != nil { + objectMap["etag"] = p.Etag + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for Pool struct. +func (p *Pool) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var poolProperties PoolProperties + err = json.Unmarshal(*v, &poolProperties) + if err != nil { + return err + } + p.PoolProperties = &poolProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + p.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + p.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + p.Type = &typeVar + } + case "etag": + if v != nil { + var etag string + err = json.Unmarshal(*v, &etag) + if err != nil { + return err + } + p.Etag = &etag + } + } + } + + return nil +} + +// PoolCreateFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type PoolCreateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *PoolCreateFuture) Result(client PoolClient) (p Pool, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.PoolCreateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("batch.PoolCreateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if p.Response.Response, err = future.GetResult(sender); err == nil && p.Response.Response.StatusCode != http.StatusNoContent { + p, err = client.CreateResponder(p.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.PoolCreateFuture", "Result", p.Response.Response, "Failure responding to request") + } + } + return +} + +// PoolDeleteFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type PoolDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *PoolDeleteFuture) Result(client PoolClient) (ar autorest.Response, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.PoolDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("batch.PoolDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// PoolEndpointConfiguration ... +type PoolEndpointConfiguration struct { + // InboundNatPools - The maximum number of inbound NAT pools per Batch pool is 5. If the maximum number of inbound NAT pools is exceeded the request fails with HTTP status code 400. + InboundNatPools *[]InboundNatPool `json:"inboundNatPools,omitempty"` +} + +// PoolProperties pool properties. +type PoolProperties struct { + // DisplayName - The display name need not be unique and can contain any Unicode characters up to a maximum length of 1024. + DisplayName *string `json:"displayName,omitempty"` + // LastModified - This is the last time at which the pool level data, such as the targetDedicatedNodes or autoScaleSettings, changed. It does not factor in node-level changes such as a compute node changing state. + LastModified *date.Time `json:"lastModified,omitempty"` + CreationTime *date.Time `json:"creationTime,omitempty"` + // ProvisioningState - Values are: + // Succeeded - The pool is available to run tasks subject to the availability of compute nodes. + // Deleting - The user has requested that the pool be deleted, but the delete operation has not yet completed. Possible values include: 'PoolProvisioningStateSucceeded', 'PoolProvisioningStateDeleting' + ProvisioningState PoolProvisioningState `json:"provisioningState,omitempty"` + ProvisioningStateTransitionTime *date.Time `json:"provisioningStateTransitionTime,omitempty"` + // AllocationState - Values are: + // Steady - The pool is not resizing. There are no changes to the number of nodes in the pool in progress. A pool enters this state when it is created and when no operations are being performed on the pool to change the number of dedicated nodes. + // Resizing - The pool is resizing; that is, compute nodes are being added to or removed from the pool. + // Stopping - The pool was resizing, but the user has requested that the resize be stopped, but the stop request has not yet been completed. Possible values include: 'Steady', 'Resizing', 'Stopping' + AllocationState AllocationState `json:"allocationState,omitempty"` + AllocationStateTransitionTime *date.Time `json:"allocationStateTransitionTime,omitempty"` + // VMSize - For information about available sizes of virtual machines for Cloud Services pools (pools created with cloudServiceConfiguration), see Sizes for Cloud Services (http://azure.microsoft.com/documentation/articles/cloud-services-sizes-specs/). Batch supports all Cloud Services VM sizes except ExtraSmall. For information about available VM sizes for pools using images from the Virtual Machines Marketplace (pools created with virtualMachineConfiguration) see Sizes for Virtual Machines (Linux) (https://azure.microsoft.com/documentation/articles/virtual-machines-linux-sizes/) or Sizes for Virtual Machines (Windows) (https://azure.microsoft.com/documentation/articles/virtual-machines-windows-sizes/). Batch supports all Azure VM sizes except STANDARD_A0 and those with premium storage (STANDARD_GS, STANDARD_DS, and STANDARD_DSV2 series). + VMSize *string `json:"vmSize,omitempty"` + // DeploymentConfiguration - Using CloudServiceConfiguration specifies that the nodes should be creating using Azure Cloud Services (PaaS), while VirtualMachineConfiguration uses Azure Virtual Machines (IaaS). + DeploymentConfiguration *DeploymentConfiguration `json:"deploymentConfiguration,omitempty"` + CurrentDedicatedNodes *int32 `json:"currentDedicatedNodes,omitempty"` + CurrentLowPriorityNodes *int32 `json:"currentLowPriorityNodes,omitempty"` + ScaleSettings *ScaleSettings `json:"scaleSettings,omitempty"` + // AutoScaleRun - This property is set only if the pool automatically scales, i.e. autoScaleSettings are used. + AutoScaleRun *AutoScaleRun `json:"autoScaleRun,omitempty"` + // InterNodeCommunication - This imposes restrictions on which nodes can be assigned to the pool. Enabling this value can reduce the chance of the requested number of nodes to be allocated in the pool. If not specified, this value defaults to 'Disabled'. Possible values include: 'Enabled', 'Disabled' + InterNodeCommunication InterNodeCommunicationState `json:"interNodeCommunication,omitempty"` + NetworkConfiguration *NetworkConfiguration `json:"networkConfiguration,omitempty"` + MaxTasksPerNode *int32 `json:"maxTasksPerNode,omitempty"` + TaskSchedulingPolicy *TaskSchedulingPolicy `json:"taskSchedulingPolicy,omitempty"` + UserAccounts *[]UserAccount `json:"userAccounts,omitempty"` + // Metadata - The Batch service does not assign any meaning to metadata; it is solely for the use of user code. + Metadata *[]MetadataItem `json:"metadata,omitempty"` + // StartTask - In an PATCH (update) operation, this property can be set to an empty object to remove the start task from the pool. + StartTask *StartTask `json:"startTask,omitempty"` + // Certificates - For Windows compute nodes, the Batch service installs the certificates to the specified certificate store and location. For Linux compute nodes, the certificates are stored in a directory inside the task working directory and an environment variable AZ_BATCH_CERTIFICATES_DIR is supplied to the task to query for this location. For certificates with visibility of 'remoteUser', a 'certs' directory is created in the user's home directory (e.g., /home/{user-name}/certs) and certificates are placed in that directory. + Certificates *[]CertificateReference `json:"certificates,omitempty"` + // ApplicationPackages - Changes to application packages affect all new compute nodes joining the pool, but do not affect compute nodes that are already in the pool until they are rebooted or reimaged. + ApplicationPackages *[]ApplicationPackageReference `json:"applicationPackages,omitempty"` + // ApplicationLicenses - The list of application licenses must be a subset of available Batch service application licenses. If a license is requested which is not supported, pool creation will fail. + ApplicationLicenses *[]string `json:"applicationLicenses,omitempty"` + ResizeOperationStatus *ResizeOperationStatus `json:"resizeOperationStatus,omitempty"` +} + +// ProxyResource a definition of an Azure resource. +type ProxyResource struct { + // ID - The ID of the resource. + ID *string `json:"id,omitempty"` + // Name - The name of the resource. + Name *string `json:"name,omitempty"` + // Type - The type of the resource. + Type *string `json:"type,omitempty"` + // Etag - The ETag of the resource, used for concurrency statements. + Etag *string `json:"etag,omitempty"` +} + +// ResizeError ... +type ResizeError struct { + // Code - An identifier for the error. Codes are invariant and are intended to be consumed programmatically. + Code *string `json:"code,omitempty"` + // Message - A message describing the error, intended to be suitable for display in a user interface. + Message *string `json:"message,omitempty"` + Details *[]ResizeError `json:"details,omitempty"` +} + +// ResizeOperationStatus describes either the current operation (if the pool AllocationState is Resizing) or the +// previously completed operation (if the AllocationState is Steady). +type ResizeOperationStatus struct { + TargetDedicatedNodes *int32 `json:"targetDedicatedNodes,omitempty"` + TargetLowPriorityNodes *int32 `json:"targetLowPriorityNodes,omitempty"` + // ResizeTimeout - The default value is 15 minutes. The minimum value is 5 minutes. If you specify a value less than 5 minutes, the Batch service returns an error; if you are calling the REST API directly, the HTTP status code is 400 (Bad Request). + ResizeTimeout *string `json:"resizeTimeout,omitempty"` + // NodeDeallocationOption - The default value is requeue. Possible values include: 'Requeue', 'Terminate', 'TaskCompletion', 'RetainedData' + NodeDeallocationOption ComputeNodeDeallocationOption `json:"nodeDeallocationOption,omitempty"` + StartTime *date.Time `json:"startTime,omitempty"` + // Errors - This property is set only if an error occurred during the last pool resize, and only when the pool allocationState is Steady. + Errors *[]ResizeError `json:"errors,omitempty"` +} + +// Resource a definition of an Azure resource. +type Resource struct { + // ID - The ID of the resource. + ID *string `json:"id,omitempty"` + // Name - The name of the resource. + Name *string `json:"name,omitempty"` + // Type - The type of the resource. + Type *string `json:"type,omitempty"` + // Location - The location of the resource. + Location *string `json:"location,omitempty"` + // Tags - The tags of the resource. + Tags map[string]*string `json:"tags"` +} + +// MarshalJSON is the custom marshaler for Resource. +func (r Resource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if r.ID != nil { + objectMap["id"] = r.ID + } + if r.Name != nil { + objectMap["name"] = r.Name + } + if r.Type != nil { + objectMap["type"] = r.Type + } + if r.Location != nil { + objectMap["location"] = r.Location + } + if r.Tags != nil { + objectMap["tags"] = r.Tags + } + return json.Marshal(objectMap) +} + +// ResourceFile ... +type ResourceFile struct { + // BlobSource - This URL must be readable using anonymous access; that is, the Batch service does not present any credentials when downloading the blob. There are two ways to get such a URL for a blob in Azure storage: include a Shared Access Signature (SAS) granting read permissions on the blob, or set the ACL for the blob or its container to allow public access. + BlobSource *string `json:"blobSource,omitempty"` + FilePath *string `json:"filePath,omitempty"` + // FileMode - This property applies only to files being downloaded to Linux compute nodes. It will be ignored if it is specified for a resourceFile which will be downloaded to a Windows node. If this property is not specified for a Linux node, then a default value of 0770 is applied to the file. + FileMode *string `json:"fileMode,omitempty"` +} + +// ScaleSettings defines the desired size of the pool. This can either be 'fixedScale' where the requested +// targetDedicatedNodes is specified, or 'autoScale' which defines a formula which is periodically reevaluated. If +// this property is not specified, the pool will have a fixed scale with 0 targetDedicatedNodes. +type ScaleSettings struct { + // FixedScale - This property and autoScale are mutually exclusive and one of the properties must be specified. + FixedScale *FixedScaleSettings `json:"fixedScale,omitempty"` + // AutoScale - This property and fixedScale are mutually exclusive and one of the properties must be specified. + AutoScale *AutoScaleSettings `json:"autoScale,omitempty"` +} + +// StartTask ... +type StartTask struct { + // CommandLine - The command line does not run under a shell, and therefore cannot take advantage of shell features such as environment variable expansion. If you want to take advantage of such features, you should invoke the shell in the command line, for example using "cmd /c MyCommand" in Windows or "/bin/sh -c MyCommand" in Linux. Required if any other properties of the startTask are specified. + CommandLine *string `json:"commandLine,omitempty"` + ResourceFiles *[]ResourceFile `json:"resourceFiles,omitempty"` + EnvironmentSettings *[]EnvironmentSetting `json:"environmentSettings,omitempty"` + // UserIdentity - If omitted, the task runs as a non-administrative user unique to the task. + UserIdentity *UserIdentity `json:"userIdentity,omitempty"` + // MaxTaskRetryCount - The Batch service retries a task if its exit code is nonzero. Note that this value specifically controls the number of retries. The Batch service will try the task once, and may then retry up to this limit. For example, if the maximum retry count is 3, Batch tries the task up to 4 times (one initial try and 3 retries). If the maximum retry count is 0, the Batch service does not retry the task. If the maximum retry count is -1, the Batch service retries the task without limit. + MaxTaskRetryCount *int32 `json:"maxTaskRetryCount,omitempty"` + // WaitForSuccess - If true and the start task fails on a compute node, the Batch service retries the start task up to its maximum retry count (maxTaskRetryCount). If the task has still not completed successfully after all retries, then the Batch service marks the compute node unusable, and will not schedule tasks to it. This condition can be detected via the node state and scheduling error detail. If false, the Batch service will not wait for the start task to complete. In this case, other tasks can start executing on the compute node while the start task is still running; and even if the start task fails, new tasks will continue to be scheduled on the node. The default is false. + WaitForSuccess *bool `json:"waitForSuccess,omitempty"` +} + +// TaskSchedulingPolicy ... +type TaskSchedulingPolicy struct { + // NodeFillType - Possible values include: 'Spread', 'Pack' + NodeFillType ComputeNodeFillType `json:"nodeFillType,omitempty"` +} + +// UserAccount ... +type UserAccount struct { + Name *string `json:"name,omitempty"` + Password *string `json:"password,omitempty"` + // ElevationLevel - nonAdmin - The auto user is a standard user without elevated access. admin - The auto user is a user with elevated access and operates with full Administrator permissions. The default value is nonAdmin. Possible values include: 'NonAdmin', 'Admin' + ElevationLevel ElevationLevel `json:"elevationLevel,omitempty"` + // LinuxUserConfiguration - This property is ignored if specified on a Windows pool. If not specified, the user is created with the default options. + LinuxUserConfiguration *LinuxUserConfiguration `json:"linuxUserConfiguration,omitempty"` +} + +// UserIdentity specify either the userName or autoUser property, but not both. +type UserIdentity struct { + // UserName - The userName and autoUser properties are mutually exclusive; you must specify one but not both. + UserName *string `json:"userName,omitempty"` + // AutoUser - The userName and autoUser properties are mutually exclusive; you must specify one but not both. + AutoUser *AutoUserSpecification `json:"autoUser,omitempty"` +} + +// VirtualMachineConfiguration ... +type VirtualMachineConfiguration struct { + ImageReference *ImageReference `json:"imageReference,omitempty"` + OsDisk *OSDisk `json:"osDisk,omitempty"` + // NodeAgentSkuID - The Batch node agent is a program that runs on each node in the pool, and provides the command-and-control interface between the node and the Batch service. There are different implementations of the node agent, known as SKUs, for different operating systems. You must specify a node agent SKU which matches the selected image reference. To get the list of supported node agent SKUs along with their list of verified image references, see the 'List supported node agent SKUs' operation. + NodeAgentSkuID *string `json:"nodeAgentSkuId,omitempty"` + // WindowsConfiguration - This property must not be specified if the imageReference specifies a Linux OS image. + WindowsConfiguration *WindowsConfiguration `json:"windowsConfiguration,omitempty"` + // DataDisks - This property must be specified if the compute nodes in the pool need to have empty data disks attached to them. + DataDisks *[]DataDisk `json:"dataDisks,omitempty"` + // LicenseType - This only applies to images that contain the Windows operating system, and should only be used when you hold valid on-premises licenses for the nodes which will be deployed. If omitted, no on-premises licensing discount is applied. Values are: + // Windows_Server - The on-premises license is for Windows Server. + // Windows_Client - The on-premises license is for Windows Client. + LicenseType *string `json:"licenseType,omitempty"` +} + +// WindowsConfiguration ... +type WindowsConfiguration struct { + // EnableAutomaticUpdates - If omitted, the default value is true. + EnableAutomaticUpdates *bool `json:"enableAutomaticUpdates,omitempty"` +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/operations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/operations.go new file mode 100644 index 000000000000..83fa8268e4cd --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/operations.go @@ -0,0 +1,126 @@ +package batch + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// OperationsClient is the client for the Operations methods of the Batch service. +type OperationsClient struct { + BaseClient +} + +// NewOperationsClient creates an instance of the OperationsClient client. +func NewOperationsClient(subscriptionID string) OperationsClient { + return NewOperationsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewOperationsClientWithBaseURI creates an instance of the OperationsClient client. +func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient { + return OperationsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// List lists available operations for the Microsoft.Batch provider +func (client OperationsClient) List(ctx context.Context) (result OperationListResultPage, err error) { + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.OperationsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.olr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "batch.OperationsClient", "List", resp, "Failure sending request") + return + } + + result.olr, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.OperationsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client OperationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPath("/providers/Microsoft.Batch/operations"), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client OperationsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client OperationsClient) ListResponder(resp *http.Response) (result OperationListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listNextResults retrieves the next set of results, if any. +func (client OperationsClient) listNextResults(lastResults OperationListResult) (result OperationListResult, err error) { + req, err := lastResults.operationListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "batch.OperationsClient", "listNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "batch.OperationsClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.OperationsClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client OperationsClient) ListComplete(ctx context.Context) (result OperationListResultIterator, err error) { + result.page, err = client.List(ctx) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/pool.go b/vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/pool.go new file mode 100644 index 000000000000..472fc28eb934 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/pool.go @@ -0,0 +1,717 @@ +package batch + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// PoolClient is the client for the Pool methods of the Batch service. +type PoolClient struct { + BaseClient +} + +// NewPoolClient creates an instance of the PoolClient client. +func NewPoolClient(subscriptionID string) PoolClient { + return NewPoolClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewPoolClientWithBaseURI creates an instance of the PoolClient client. +func NewPoolClientWithBaseURI(baseURI string, subscriptionID string) PoolClient { + return PoolClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Create creates a new pool inside the specified account. +// Parameters: +// resourceGroupName - the name of the resource group that contains the Batch account. +// accountName - the name of the Batch account. +// poolName - the pool name. This must be unique within the account. +// parameters - additional parameters for pool creation. +// ifMatch - the entity state (ETag) version of the pool to update. A value of "*" can be used to apply the +// operation only if the pool already exists. If omitted, this operation will always be applied. +// ifNoneMatch - set to '*' to allow a new pool to be created, but to prevent updating an existing pool. Other +// values will be ignored. +func (client PoolClient) Create(ctx context.Context, resourceGroupName string, accountName string, poolName string, parameters Pool, ifMatch string, ifNoneMatch string) (result PoolCreateFuture, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}, + {Target: "accountName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}, + {TargetValue: poolName, + Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_-]+$`, Chain: nil}}}, + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.PoolProperties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.PoolProperties.DeploymentConfiguration", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.PoolProperties.DeploymentConfiguration.CloudServiceConfiguration", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.PoolProperties.DeploymentConfiguration.CloudServiceConfiguration.OsFamily", Name: validation.Null, Rule: true, Chain: nil}}}, + {Target: "parameters.PoolProperties.DeploymentConfiguration.VirtualMachineConfiguration", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.PoolProperties.DeploymentConfiguration.VirtualMachineConfiguration.ImageReference", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.PoolProperties.DeploymentConfiguration.VirtualMachineConfiguration.NodeAgentSkuID", Name: validation.Null, Rule: true, Chain: nil}, + }}, + }}, + {Target: "parameters.PoolProperties.ScaleSettings", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.PoolProperties.ScaleSettings.AutoScale", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.PoolProperties.ScaleSettings.AutoScale.Formula", Name: validation.Null, Rule: true, Chain: nil}}}, + }}, + {Target: "parameters.PoolProperties.AutoScaleRun", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.PoolProperties.AutoScaleRun.EvaluationTime", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.PoolProperties.AutoScaleRun.Error", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.PoolProperties.AutoScaleRun.Error.Code", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.PoolProperties.AutoScaleRun.Error.Message", Name: validation.Null, Rule: true, Chain: nil}, + }}, + }}, + {Target: "parameters.PoolProperties.NetworkConfiguration", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.PoolProperties.NetworkConfiguration.EndpointConfiguration", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.PoolProperties.NetworkConfiguration.EndpointConfiguration.InboundNatPools", Name: validation.Null, Rule: true, Chain: nil}}}, + }}, + }}}}}); err != nil { + return result, validation.NewError("batch.PoolClient", "Create", err.Error()) + } + + req, err := client.CreatePreparer(ctx, resourceGroupName, accountName, poolName, parameters, ifMatch, ifNoneMatch) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.PoolClient", "Create", nil, "Failure preparing request") + return + } + + result, err = client.CreateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.PoolClient", "Create", result.Response(), "Failure sending request") + return + } + + return +} + +// CreatePreparer prepares the Create request. +func (client PoolClient) CreatePreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, parameters Pool, ifMatch string, ifNoneMatch string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "poolName": autorest.Encode("path", poolName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + if len(ifMatch) > 0 { + preparer = autorest.DecoratePreparer(preparer, + autorest.WithHeader("If-Match", autorest.String(ifMatch))) + } + if len(ifNoneMatch) > 0 { + preparer = autorest.DecoratePreparer(preparer, + autorest.WithHeader("If-None-Match", autorest.String(ifNoneMatch))) + } + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateSender sends the Create request. The method will close the +// http.Response Body if it receives an error. +func (client PoolClient) CreateSender(req *http.Request) (future PoolCreateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// CreateResponder handles the response to the Create request. The method always +// closes the http.Response Body. +func (client PoolClient) CreateResponder(resp *http.Response) (result Pool, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes the specified pool. +// Parameters: +// resourceGroupName - the name of the resource group that contains the Batch account. +// accountName - the name of the Batch account. +// poolName - the pool name. This must be unique within the account. +func (client PoolClient) Delete(ctx context.Context, resourceGroupName string, accountName string, poolName string) (result PoolDeleteFuture, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}, + {Target: "accountName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}, + {TargetValue: poolName, + Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_-]+$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("batch.PoolClient", "Delete", err.Error()) + } + + req, err := client.DeletePreparer(ctx, resourceGroupName, accountName, poolName) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.PoolClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.PoolClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client PoolClient) DeletePreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "poolName": autorest.Encode("path", poolName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client PoolClient) DeleteSender(req *http.Request) (future PoolDeleteFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client PoolClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// DisableAutoScale disables automatic scaling for a pool. +// Parameters: +// resourceGroupName - the name of the resource group that contains the Batch account. +// accountName - the name of the Batch account. +// poolName - the pool name. This must be unique within the account. +func (client PoolClient) DisableAutoScale(ctx context.Context, resourceGroupName string, accountName string, poolName string) (result Pool, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}, + {Target: "accountName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}, + {TargetValue: poolName, + Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_-]+$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("batch.PoolClient", "DisableAutoScale", err.Error()) + } + + req, err := client.DisableAutoScalePreparer(ctx, resourceGroupName, accountName, poolName) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.PoolClient", "DisableAutoScale", nil, "Failure preparing request") + return + } + + resp, err := client.DisableAutoScaleSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "batch.PoolClient", "DisableAutoScale", resp, "Failure sending request") + return + } + + result, err = client.DisableAutoScaleResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.PoolClient", "DisableAutoScale", resp, "Failure responding to request") + } + + return +} + +// DisableAutoScalePreparer prepares the DisableAutoScale request. +func (client PoolClient) DisableAutoScalePreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "poolName": autorest.Encode("path", poolName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}/disableAutoScale", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DisableAutoScaleSender sends the DisableAutoScale request. The method will close the +// http.Response Body if it receives an error. +func (client PoolClient) DisableAutoScaleSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// DisableAutoScaleResponder handles the response to the DisableAutoScale request. The method always +// closes the http.Response Body. +func (client PoolClient) DisableAutoScaleResponder(resp *http.Response) (result Pool, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Get gets information about the specified pool. +// Parameters: +// resourceGroupName - the name of the resource group that contains the Batch account. +// accountName - the name of the Batch account. +// poolName - the pool name. This must be unique within the account. +func (client PoolClient) Get(ctx context.Context, resourceGroupName string, accountName string, poolName string) (result Pool, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}, + {Target: "accountName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}, + {TargetValue: poolName, + Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_-]+$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("batch.PoolClient", "Get", err.Error()) + } + + req, err := client.GetPreparer(ctx, resourceGroupName, accountName, poolName) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.PoolClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "batch.PoolClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.PoolClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client PoolClient) GetPreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "poolName": autorest.Encode("path", poolName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client PoolClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client PoolClient) GetResponder(resp *http.Response) (result Pool, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByBatchAccount lists all of the pools in the specified account. +// Parameters: +// resourceGroupName - the name of the resource group that contains the Batch account. +// accountName - the name of the Batch account. +// maxresults - the maximum number of items to return in the response. +// selectParameter - comma separated list of properties that should be returned. e.g. +// "properties/provisioningState". Only top level properties under properties/ are valid for selection. +// filter - oData filter expression. Valid properties for filtering are: +// +// name +// properties/allocationState +// properties/allocationStateTransitionTime +// properties/creationTime +// properties/provisioningState +// properties/provisioningStateTransitionTime +// properties/lastModified +// properties/vmSize +// properties/interNodeCommunication +// properties/scaleSettings/autoScale +// properties/scaleSettings/fixedScale +func (client PoolClient) ListByBatchAccount(ctx context.Context, resourceGroupName string, accountName string, maxresults *int32, selectParameter string, filter string) (result ListPoolsResultPage, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}, + {Target: "accountName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("batch.PoolClient", "ListByBatchAccount", err.Error()) + } + + result.fn = client.listByBatchAccountNextResults + req, err := client.ListByBatchAccountPreparer(ctx, resourceGroupName, accountName, maxresults, selectParameter, filter) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.PoolClient", "ListByBatchAccount", nil, "Failure preparing request") + return + } + + resp, err := client.ListByBatchAccountSender(req) + if err != nil { + result.lpr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "batch.PoolClient", "ListByBatchAccount", resp, "Failure sending request") + return + } + + result.lpr, err = client.ListByBatchAccountResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.PoolClient", "ListByBatchAccount", resp, "Failure responding to request") + } + + return +} + +// ListByBatchAccountPreparer prepares the ListByBatchAccount request. +func (client PoolClient) ListByBatchAccountPreparer(ctx context.Context, resourceGroupName string, accountName string, maxresults *int32, selectParameter string, filter string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if maxresults != nil { + queryParameters["maxresults"] = autorest.Encode("query", *maxresults) + } + if len(selectParameter) > 0 { + queryParameters["$select"] = autorest.Encode("query", selectParameter) + } + if len(filter) > 0 { + queryParameters["$filter"] = autorest.Encode("query", filter) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByBatchAccountSender sends the ListByBatchAccount request. The method will close the +// http.Response Body if it receives an error. +func (client PoolClient) ListByBatchAccountSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByBatchAccountResponder handles the response to the ListByBatchAccount request. The method always +// closes the http.Response Body. +func (client PoolClient) ListByBatchAccountResponder(resp *http.Response) (result ListPoolsResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByBatchAccountNextResults retrieves the next set of results, if any. +func (client PoolClient) listByBatchAccountNextResults(lastResults ListPoolsResult) (result ListPoolsResult, err error) { + req, err := lastResults.listPoolsResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "batch.PoolClient", "listByBatchAccountNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByBatchAccountSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "batch.PoolClient", "listByBatchAccountNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByBatchAccountResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.PoolClient", "listByBatchAccountNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByBatchAccountComplete enumerates all values, automatically crossing page boundaries as required. +func (client PoolClient) ListByBatchAccountComplete(ctx context.Context, resourceGroupName string, accountName string, maxresults *int32, selectParameter string, filter string) (result ListPoolsResultIterator, err error) { + result.page, err = client.ListByBatchAccount(ctx, resourceGroupName, accountName, maxresults, selectParameter, filter) + return +} + +// StopResize this does not restore the pool to its previous state before the resize operation: it only stops any +// further changes being made, and the pool maintains its current state. After stopping, the pool stabilizes at the +// number of nodes it was at when the stop operation was done. During the stop operation, the pool allocation state +// changes first to stopping and then to steady. A resize operation need not be an explicit resize pool request; this +// API can also be used to halt the initial sizing of the pool when it is created. +// Parameters: +// resourceGroupName - the name of the resource group that contains the Batch account. +// accountName - the name of the Batch account. +// poolName - the pool name. This must be unique within the account. +func (client PoolClient) StopResize(ctx context.Context, resourceGroupName string, accountName string, poolName string) (result Pool, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}, + {Target: "accountName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}, + {TargetValue: poolName, + Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_-]+$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("batch.PoolClient", "StopResize", err.Error()) + } + + req, err := client.StopResizePreparer(ctx, resourceGroupName, accountName, poolName) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.PoolClient", "StopResize", nil, "Failure preparing request") + return + } + + resp, err := client.StopResizeSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "batch.PoolClient", "StopResize", resp, "Failure sending request") + return + } + + result, err = client.StopResizeResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.PoolClient", "StopResize", resp, "Failure responding to request") + } + + return +} + +// StopResizePreparer prepares the StopResize request. +func (client PoolClient) StopResizePreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "poolName": autorest.Encode("path", poolName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}/stopResize", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// StopResizeSender sends the StopResize request. The method will close the +// http.Response Body if it receives an error. +func (client PoolClient) StopResizeSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// StopResizeResponder handles the response to the StopResize request. The method always +// closes the http.Response Body. +func (client PoolClient) StopResizeResponder(resp *http.Response) (result Pool, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Update updates the properties of an existing pool. +// Parameters: +// resourceGroupName - the name of the resource group that contains the Batch account. +// accountName - the name of the Batch account. +// poolName - the pool name. This must be unique within the account. +// parameters - pool properties that should be updated. Properties that are supplied will be updated, any +// property not supplied will be unchanged. +// ifMatch - the entity state (ETag) version of the pool to update. This value can be omitted or set to "*" to +// apply the operation unconditionally. +func (client PoolClient) Update(ctx context.Context, resourceGroupName string, accountName string, poolName string, parameters Pool, ifMatch string) (result Pool, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}, + {Target: "accountName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}, + {TargetValue: poolName, + Constraints: []validation.Constraint{{Target: "poolName", Name: validation.MaxLength, Rule: 64, Chain: nil}, + {Target: "poolName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "poolName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9_-]+$`, Chain: nil}}}}); err != nil { + return result, validation.NewError("batch.PoolClient", "Update", err.Error()) + } + + req, err := client.UpdatePreparer(ctx, resourceGroupName, accountName, poolName, parameters, ifMatch) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.PoolClient", "Update", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "batch.PoolClient", "Update", resp, "Failure sending request") + return + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "batch.PoolClient", "Update", resp, "Failure responding to request") + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client PoolClient) UpdatePreparer(ctx context.Context, resourceGroupName string, accountName string, poolName string, parameters Pool, ifMatch string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "poolName": autorest.Encode("path", poolName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-09-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/pools/{poolName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + if len(ifMatch) > 0 { + preparer = autorest.DecoratePreparer(preparer, + autorest.WithHeader("If-Match", autorest.String(ifMatch))) + } + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// UpdateSender sends the Update request. The method will close the +// http.Response Body if it receives an error. +func (client PoolClient) UpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client PoolClient) UpdateResponder(resp *http.Response) (result Pool, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/version.go b/vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/version.go new file mode 100644 index 000000000000..e702917772da --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch/version.go @@ -0,0 +1,30 @@ +package batch + +import "github.com/Azure/azure-sdk-for-go/version" + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +// UserAgent returns the UserAgent string to use when sending http.Requests. +func UserAgent() string { + return "Azure-SDK-For-Go/" + version.Number + " batch/2017-09-01" +} + +// Version returns the semantic version (see http://semver.org) of the client. +func Version() string { + return version.Number +} diff --git a/vendor/vendor.json b/vendor/vendor.json index 4a1fd54ea316..cfc38ebe87af 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -26,6 +26,14 @@ "version": "v21.3.0", "versionExact": "v21.3.0" }, + { + "checksumSHA1": "wSU0j8sK/9pDbS+X4jxvExz44w8=", + "path": "github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch", + "revision": "da91af54816b4cf72949c225a2d0980f51fab01b", + "revisionTime": "2018-10-19T17:11:53Z", + "version": "v21.3.0", + "versionExact": "v21.3.0" + }, { "checksumSHA1": "GZEKIkiC//1VgeihW1g/KU+JC8A=", "path": "github.com/Azure/azure-sdk-for-go/services/cdn/mgmt/2017-10-12/cdn", From c942f083bc76e88b3678821b9e0a53e072650be1 Mon Sep 17 00:00:00 2001 From: Julien Corioland Date: Mon, 3 Dec 2018 17:58:06 +0100 Subject: [PATCH 03/13] wip: add datasource & resource for batch account --- azurerm/config.go | 11 ++ azurerm/data_source_batch_account.go | 74 +++++++++ azurerm/data_source_batch_account_test.go | 50 ++++++ azurerm/provider.go | 2 + azurerm/resource_arm_batch_account.go | 175 +++++++++++++++++++++ azurerm/resource_arm_batch_account_test.go | 116 ++++++++++++++ 6 files changed, 428 insertions(+) create mode 100644 azurerm/data_source_batch_account.go create mode 100644 azurerm/data_source_batch_account_test.go create mode 100644 azurerm/resource_arm_batch_account.go create mode 100644 azurerm/resource_arm_batch_account_test.go diff --git a/azurerm/config.go b/azurerm/config.go index df8177dccd5e..6c1cd77f8c43 100644 --- a/azurerm/config.go +++ b/azurerm/config.go @@ -12,6 +12,7 @@ import ( "github.com/Azure/azure-sdk-for-go/profiles/2017-03-09/resources/mgmt/resources" appinsights "github.com/Azure/azure-sdk-for-go/services/appinsights/mgmt/2015-05-01/insights" "github.com/Azure/azure-sdk-for-go/services/automation/mgmt/2015-10-31/automation" + "github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch" "github.com/Azure/azure-sdk-for-go/services/cdn/mgmt/2017-10-12/cdn" "github.com/Azure/azure-sdk-for-go/services/cognitiveservices/mgmt/2017-04-18/cognitiveservices" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-06-01/compute" @@ -133,6 +134,9 @@ type ArmClient struct { // Autoscale Settings autoscaleSettingsClient insights.AutoscaleSettingsClient + // Batch + batchAccountClient batch.AccountClient + // CDN cdnCustomDomainsClient cdn.CustomDomainsClient cdnEndpointsClient cdn.EndpointsClient @@ -415,6 +419,7 @@ func getArmClient(c *authentication.Config, skipProviderRegistration bool) (*Arm client.registerAppInsightsClients(endpoint, c.SubscriptionID, auth) client.registerAutomationClients(endpoint, c.SubscriptionID, auth) client.registerAuthentication(endpoint, graphEndpoint, c.SubscriptionID, c.TenantID, auth, graphAuth) + client.registerBatchClients(endpoint, c.SubscriptionID, auth) client.registerCDNClients(endpoint, c.SubscriptionID, auth) client.registerCognitiveServiceClients(endpoint, c.SubscriptionID, auth) client.registerComputeClients(endpoint, c.SubscriptionID, auth) @@ -523,6 +528,12 @@ func (c *ArmClient) registerAuthentication(endpoint, graphEndpoint, subscription c.servicePrincipalsClient = servicePrincipalsClient } +func (c *ArmClient) registerBatchClients(endpoint, subscriptionId string, auth autorest.Authorizer) { + batchAccount := batch.NewAccountClientWithBaseURI(endpoint, subscriptionId) + c.configureClient(&batchAccount.Client, auth) + c.batchAccountClient = batchAccount +} + func (c *ArmClient) registerCDNClients(endpoint, subscriptionId string, auth autorest.Authorizer) { customDomainsClient := cdn.NewCustomDomainsClientWithBaseURI(endpoint, subscriptionId) c.configureClient(&customDomainsClient.Client, auth) diff --git a/azurerm/data_source_batch_account.go b/azurerm/data_source_batch_account.go new file mode 100644 index 000000000000..d7312df7e607 --- /dev/null +++ b/azurerm/data_source_batch_account.go @@ -0,0 +1,74 @@ +package azurerm + +import ( + "fmt" + + "github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch" + + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func dataSourceArmBatchAccount() *schema.Resource { + return &schema.Resource{ + Read: dataSourceArmBatchAccountRead, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validateAzureRMBatchAccountName, + }, + "resource_group_name": resourceGroupNameDiffSuppressSchema(), + "location": locationForDataSourceSchema(), + "storage_account_id": { + Type: schema.TypeString, + Computed: true, + }, + "pool_allocation_mode": { + Type: schema.TypeString, + Optional: true, + Default: string(batch.BatchService), + DiffSuppressFunc: ignoreCaseDiffSuppressFunc, + ValidateFunc: validation.StringInSlice([]string{ + string(batch.BatchService), + string(batch.UserSubscription), + }, true), + }, + "tags": tagsForDataSourceSchema(), + }, + } +} + +func dataSourceArmBatchAccountRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).batchAccountClient + + resourceGroup := d.Get("resource_group_name").(string) + name := d.Get("name").(string) + + ctx := meta.(*ArmClient).StopContext + resp, err := client.Get(ctx, resourceGroup, name) + + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + return fmt.Errorf("Error: Batch account %q (Resource Group %q) was not found", name, resourceGroup) + } + return fmt.Errorf("Error making Read request on AzureRM Batch account %q: %+v", name, err) + } + + // todo : fetch properties + + d.SetId(*resp.ID) + + d.Set("name", name) + d.Set("resource_group_name", resourceGroup) + if location := resp.Location; location != nil { + d.Set("location", azureRMNormalizeLocation(*location)) + } + + flattenAndSetTags(d, resp.Tags) + + return nil +} diff --git a/azurerm/data_source_batch_account_test.go b/azurerm/data_source_batch_account_test.go new file mode 100644 index 000000000000..2f97cbeda897 --- /dev/null +++ b/azurerm/data_source_batch_account_test.go @@ -0,0 +1,50 @@ +package azurerm + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" +) + +func TestAccDataSourceAzureRMBatchAccount_basic(t *testing.T) { + dataSourceName := "data.azurerm_batch_account.test" + ri := acctest.RandInt() + name := fmt.Sprintf("acctestbatchaccount%d", ri) + location := testLocation() + config := testAccDataSourceAzureRMBatchAccount_basic(name, location) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(dataSourceName, "name", name), + resource.TestCheckResourceAttr(dataSourceName, "location", azureRMNormalizeLocation(location)), + resource.TestCheckResourceAttr(dataSourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(dataSourceName, "tags.env", "test"), + ), + }, + }, + }) +} + +func testAccDataSourceAzureRMBatchAccount_basic(name string, location string) string { + return fmt.Sprintf(` +resource "azurerm_batch_account" "test" { + name = "%s" + location = "%s" + + tags { + env = "test" + } +} + +data "azurerm_batch_account" "test" { + name = "${azurerm_batch_account.test.name}" + } +`, name, location) +} diff --git a/azurerm/provider.go b/azurerm/provider.go index 9336bc664ac2..db3275ba5182 100644 --- a/azurerm/provider.go +++ b/azurerm/provider.go @@ -78,6 +78,7 @@ func Provider() terraform.ResourceProvider { "azurerm_application_security_group": dataSourceArmApplicationSecurityGroup(), "azurerm_app_service": dataSourceArmAppService(), "azurerm_app_service_plan": dataSourceAppServicePlan(), + "azurerm_batch_account": dataSourceArmBatchAccount(), "azurerm_builtin_role_definition": dataSourceArmBuiltInRoleDefinition(), "azurerm_cdn_profile": dataSourceArmCdnProfile(), "azurerm_client_config": dataSourceArmClientConfig(), @@ -147,6 +148,7 @@ func Provider() terraform.ResourceProvider { "azurerm_automation_schedule": resourceArmAutomationSchedule(), "azurerm_autoscale_setting": resourceArmAutoScaleSetting(), "azurerm_availability_set": resourceArmAvailabilitySet(), + "azurerm_batch_account": resourceArmBatchAccount(), "azurerm_cdn_endpoint": resourceArmCdnEndpoint(), "azurerm_cdn_profile": resourceArmCdnProfile(), "azurerm_cognitive_account": resourceArmCognitiveAccount(), diff --git a/azurerm/resource_arm_batch_account.go b/azurerm/resource_arm_batch_account.go new file mode 100644 index 000000000000..7e2b62aa622d --- /dev/null +++ b/azurerm/resource_arm_batch_account.go @@ -0,0 +1,175 @@ +package azurerm + +import ( + "fmt" + "regexp" + + "github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch" + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func resourceArmBatchAccount() *schema.Resource { + return &schema.Resource{ + Create: resourceArmBatchAccountCreate, + Read: resourceArmBatchAccountRead, + Update: resourceArmBatchAccountUpdate, + Delete: resourceArmBatchAccountDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validateAzureRMBatchAccountName, + }, + "resource_group_name": resourceGroupNameDiffSuppressSchema(), + "location": locationSchema(), + "storage_account_id": { + Type: schema.TypeString, + Optional: true, + }, + "pool_allocation_mode": { + Type: schema.TypeString, + Optional: true, + Default: string(batch.BatchService), + DiffSuppressFunc: ignoreCaseDiffSuppressFunc, + ValidateFunc: validation.StringInSlice([]string{ + string(batch.BatchService), + string(batch.UserSubscription), + }, true), + }, + "tags": tagsSchema(), + }, + } +} + +func resourceArmBatchAccountCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).batchAccountClient + ctx := meta.(*ArmClient).StopContext + + resourceGroupName := d.Get("resource_group_name").(string) + name := d.Get("name").(string) + location := azureRMNormalizeLocation(d.Get("location").(string)) + storageAccountId := d.Get("storage_account_id").(string) + poolAllocationMode := d.Get("pool_allocation_mode").(string) + tags := d.Get("tags").(map[string]interface{}) + + parameters := batch.AccountCreateParameters{ + Location: &location, + AccountCreateProperties: &batch.AccountCreateProperties{ + AutoStorage: &batch.AutoStorageBaseProperties{ + StorageAccountID: &storageAccountId, + }, + PoolAllocationMode: batch.PoolAllocationMode(poolAllocationMode), + }, + Tags: expandTags(tags), + } + + future, err := client.Create(ctx, resourceGroupName, name, parameters) + if err != nil { + return fmt.Errorf("Error creating Batch account %q (Resource Group %q): %+v", name, resourceGroupName, err) + } + + err = future.WaitForCompletionRef(ctx, client.Client) + if err != nil { + return fmt.Errorf("Error waiting for creation of Batch account %q (Resource Group %q): %+v", name, resourceGroupName, err) + } + + read, err := client.Get(ctx, resourceGroupName, name) + if err != nil { + return fmt.Errorf("Error retrieving Batch account %q (Resource Group %q): %+v", name, resourceGroupName, err) + } + + if read.ID == nil { + return fmt.Errorf("Cannot read Batch account %q (resource group %q) ID", name, resourceGroupName) + } + + d.SetId(*read.ID) + + return resourceArmBatchAccountRead(d, meta) +} + +func resourceArmBatchAccountRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).batchAccountClient + ctx := meta.(*ArmClient).StopContext + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + name := id.Path["batchAccounts"] + resourceGroupName := id.ResourceGroup + + resp, err := client.Get(ctx, resourceGroupName, name) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + d.SetId("") + return nil + } + return fmt.Errorf("Error reading the state of Batch account %q: %+v", name, err) + } + + d.Set("name", resp.Name) + d.Set("resource_group_name", resourceGroupName) + d.Set("location", resp.Location) + d.Set("pool_allocation_mode", resp.PoolAllocationMode) + + if resp.AutoStorage != nil { + d.Set("storage_acount_id", resp.AutoStorage.StorageAccountID) + } + + flattenAndSetTags(d, resp.Tags) + + return nil +} + +func resourceArmBatchAccountUpdate(d *schema.ResourceData, meta interface{}) error { + return nil +} + +func resourceArmBatchAccountDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).batchAccountClient + ctx := meta.(*ArmClient).StopContext + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + name := id.Path["batchAccounts"] + resourceGroupName := id.ResourceGroup + + future, err := client.Delete(ctx, resourceGroupName, name) + if err != nil { + return fmt.Errorf("Error deleting Batch account %q (Resource Group %q): %+v", name, resourceGroupName, err) + } + + err = future.WaitForCompletionRef(ctx, client.Client) + if err != nil { + return fmt.Errorf("Error waiting for deletion of Batch account %q (Resource Group %q): %+v", name, resourceGroupName, err) + } + + return nil +} + +func validateAzureRMBatchAccountName(v interface{}, k string) (warnings []string, errors []error) { + value := v.(string) + if !regexp.MustCompile(`^[a-z0-9]+$`).MatchString(value) { + errors = append(errors, fmt.Errorf( + "lowercase letters and numbers only are allowed in %q: %q", k, value)) + } + + if 3 > len(value) { + errors = append(errors, fmt.Errorf("%q cannot be less than 3 characters: %q", k, value)) + } + + if len(value) > 24 { + errors = append(errors, fmt.Errorf("%q cannot be longer than 24 characters: %q %d", k, value, len(value))) + } + + return warnings, errors +} diff --git a/azurerm/resource_arm_batch_account_test.go b/azurerm/resource_arm_batch_account_test.go new file mode 100644 index 000000000000..18e78552c890 --- /dev/null +++ b/azurerm/resource_arm_batch_account_test.go @@ -0,0 +1,116 @@ +package azurerm + +import ( + "fmt" + "net/http" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestValidateBatchAccountName(t *testing.T) { + testCases := []struct { + input string + shouldError bool + }{ + {"ab", true}, + {"ABC", true}, + {"abc", false}, + {"123456789012345678901234", false}, + {"1234567890123456789012345", true}, + {"abc12345", false}, + } + + for _, test := range testCases { + _, es := validateAzureRMBatchAccountName(test.input, "name") + + if test.shouldError && len(es) == 0 { + t.Fatalf("Expected validating name %q to fail", test.input) + } + } +} + +func TestAccAzureRMBatchAccount_basic(t *testing.T) { + resourceName := "azurerm_batch_account.test" + ri := acctest.RandInt() + rs := acctest.RandString(4) + location := testLocation() + + config := testAccAzureRMBatchAccount_basic(ri, rs, location) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + // CheckDestroy: testCheckAzureRMStorageAccountDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMBatchAccountExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "pool_allocation_mode", "BatchService"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.env", "test"), + ), + }, + }, + }) +} + +func testCheckAzureRMBatchAccountExists(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + // Ensure we have enough information in state to look up in API + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + batchAccount := rs.Primary.Attributes["name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] + + // Ensure resource group exists in API + ctx := testAccProvider.Meta().(*ArmClient).StopContext + conn := testAccProvider.Meta().(*ArmClient).batchAccountClient + + resp, err := conn.Get(ctx, resourceGroup, batchAccount) + if err != nil { + return fmt.Errorf("Bad: Get on batchAccountClient: %+v", err) + } + + if resp.StatusCode == http.StatusNotFound { + return fmt.Errorf("Bad: Batch account %q (resource group: %q) does not exist", name, resourceGroup) + } + + return nil + } +} + +func testAccAzureRMBatchAccount_basic(rInt int, rString string, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "testaccbatch%d" + location = "%s" +} + +resource "azurerm_storage_account" "test" { + name = "testaccsa%s" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + account_tier = "Standard" + account_replication_type = "LRS" + } + +resource "azurerm_batch_account" "test" { + name = "testaccbatch%s" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + pool_allocation_mode = "BatchService" + storage_account_id = "${azurerm_storage_account.test.id}" + + tags { + env = "test" + } +} +`, rInt, location, rString, rString) +} From 42a73a441167aa5e334e6b3d3f9e63d3cd2ce140 Mon Sep 17 00:00:00 2001 From: Julien Corioland Date: Tue, 4 Dec 2018 14:30:03 +0100 Subject: [PATCH 04/13] CRUD for Azure Batch account + tests --- azurerm/resource_arm_batch_account.go | 62 +++++++++++++--- azurerm/resource_arm_batch_account_test.go | 82 ++++++++++++++++++++-- 2 files changed, 129 insertions(+), 15 deletions(-) diff --git a/azurerm/resource_arm_batch_account.go b/azurerm/resource_arm_batch_account.go index 7e2b62aa622d..ca31a103df6a 100644 --- a/azurerm/resource_arm_batch_account.go +++ b/azurerm/resource_arm_batch_account.go @@ -2,11 +2,13 @@ package azurerm import ( "fmt" + "log" "regexp" "github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch" "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/helper/validation" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -30,18 +32,18 @@ func resourceArmBatchAccount() *schema.Resource { "resource_group_name": resourceGroupNameDiffSuppressSchema(), "location": locationSchema(), "storage_account_id": { - Type: schema.TypeString, - Optional: true, + Type: schema.TypeString, + Optional: true, + ValidateFunc: azure.ValidateResourceIDOrEmpty, }, "pool_allocation_mode": { - Type: schema.TypeString, - Optional: true, - Default: string(batch.BatchService), - DiffSuppressFunc: ignoreCaseDiffSuppressFunc, + Type: schema.TypeString, + Optional: true, + Default: string(batch.BatchService), ValidateFunc: validation.StringInSlice([]string{ string(batch.BatchService), string(batch.UserSubscription), - }, true), + }, false), }, "tags": tagsSchema(), }, @@ -52,6 +54,8 @@ func resourceArmBatchAccountCreate(d *schema.ResourceData, meta interface{}) err client := meta.(*ArmClient).batchAccountClient ctx := meta.(*ArmClient).StopContext + log.Printf("[INFO] preparing arguments for Azure Batch account creation.") + resourceGroupName := d.Get("resource_group_name").(string) name := d.Get("name").(string) location := azureRMNormalizeLocation(d.Get("location").(string)) @@ -109,6 +113,7 @@ func resourceArmBatchAccountRead(d *schema.ResourceData, meta interface{}) error if err != nil { if utils.ResponseWasNotFound(resp.Response) { d.SetId("") + log.Printf("[DEBUG] Batch Account %q was not found in Resource Group %q - removing from state!", name, resourceGroupName) return nil } return fmt.Errorf("Error reading the state of Batch account %q: %+v", name, err) @@ -116,9 +121,12 @@ func resourceArmBatchAccountRead(d *schema.ResourceData, meta interface{}) error d.Set("name", resp.Name) d.Set("resource_group_name", resourceGroupName) - d.Set("location", resp.Location) d.Set("pool_allocation_mode", resp.PoolAllocationMode) + if location := resp.Location; location != nil { + d.Set("location", azureRMNormalizeLocation(*location)) + } + if resp.AutoStorage != nil { d.Set("storage_acount_id", resp.AutoStorage.StorageAccountID) } @@ -129,7 +137,43 @@ func resourceArmBatchAccountRead(d *schema.ResourceData, meta interface{}) error } func resourceArmBatchAccountUpdate(d *schema.ResourceData, meta interface{}) error { - return nil + client := meta.(*ArmClient).batchAccountClient + ctx := meta.(*ArmClient).StopContext + + log.Printf("[INFO] preparing arguments for Azure Batch account update.") + + resourceGroupName := d.Get("resource_group_name").(string) + name := d.Get("name").(string) + + storageAccountId := d.Get("storage_account_id").(string) + tags := d.Get("tags").(map[string]interface{}) + + parameters := batch.AccountUpdateParameters{ + AccountUpdateProperties: &batch.AccountUpdateProperties{ + AutoStorage: &batch.AutoStorageBaseProperties{ + StorageAccountID: &storageAccountId, + }, + }, + Tags: expandTags(tags), + } + + _, err := client.Update(ctx, resourceGroupName, name, parameters) + if err != nil { + return fmt.Errorf("Error updating Batch account %q (Resource Group %q): %+v", name, resourceGroupName, err) + } + + read, err := client.Get(ctx, resourceGroupName, name) + if err != nil { + return fmt.Errorf("Error retrieving Batch account %q (Resource Group %q): %+v", name, resourceGroupName, err) + } + + if read.ID == nil { + return fmt.Errorf("Cannot read Batch account %q (resource group %q) ID", name, resourceGroupName) + } + + d.SetId(*read.ID) + + return resourceArmBatchAccountRead(d, meta) } func resourceArmBatchAccountDelete(d *schema.ResourceData, meta interface{}) error { diff --git a/azurerm/resource_arm_batch_account_test.go b/azurerm/resource_arm_batch_account_test.go index 18e78552c890..94cc1d3b3859 100644 --- a/azurerm/resource_arm_batch_account_test.go +++ b/azurerm/resource_arm_batch_account_test.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) func TestValidateBatchAccountName(t *testing.T) { @@ -36,15 +37,18 @@ func TestAccAzureRMBatchAccount_basic(t *testing.T) { resourceName := "azurerm_batch_account.test" ri := acctest.RandInt() rs := acctest.RandString(4) + rs2 := acctest.RandString(4) location := testLocation() - config := testAccAzureRMBatchAccount_basic(ri, rs, location) + config := testAccAzureRMBatchAccount_basic(ri, rs, rs, location) + configUpdate := testAccAzureRMBatchAccount_basicUpdate(ri, rs2, rs, location) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - // CheckDestroy: testCheckAzureRMStorageAccountDestroy, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMBatchAccountDestroy, Steps: []resource.TestStep{ + // Create { Config: config, Check: resource.ComposeTestCheckFunc( @@ -54,6 +58,17 @@ func TestAccAzureRMBatchAccount_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "tags.env", "test"), ), }, + // Update + { + Config: configUpdate, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMBatchAccountExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "pool_allocation_mode", "BatchService"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.env", "test"), + resource.TestCheckResourceAttr(resourceName, "tags.version", "2"), + ), + }, }, }) } @@ -86,7 +101,32 @@ func testCheckAzureRMBatchAccountExists(name string) resource.TestCheckFunc { } } -func testAccAzureRMBatchAccount_basic(rInt int, rString string, location string) string { +func testCheckAzureRMBatchAccountDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*ArmClient).batchAccountClient + ctx := testAccProvider.Meta().(*ArmClient).StopContext + + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_batch_account" { + continue + } + + name := rs.Primary.Attributes["name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] + + resp, err := conn.Get(ctx, resourceGroup, name) + if err != nil { + if !utils.ResponseWasNotFound(resp.Response) { + return err + } + } + + return nil + } + + return nil +} + +func testAccAzureRMBatchAccount_basic(rInt int, storageSuffix string, batchAccountSuffix string, location string) string { return fmt.Sprintf(` resource "azurerm_resource_group" "test" { name = "testaccbatch%d" @@ -112,5 +152,35 @@ resource "azurerm_batch_account" "test" { env = "test" } } -`, rInt, location, rString, rString) +`, rInt, location, storageSuffix, batchAccountSuffix) +} + +func testAccAzureRMBatchAccount_basicUpdate(rInt int, storageSuffix string, batchAccountSuffix string, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "testaccbatch%d" + location = "%s" +} + +resource "azurerm_storage_account" "test" { + name = "testaccsa%s" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + account_tier = "Standard" + account_replication_type = "LRS" + } + +resource "azurerm_batch_account" "test" { + name = "testaccbatch%s" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + pool_allocation_mode = "BatchService" + storage_account_id = "${azurerm_storage_account.test.id}" + + tags { + env = "test" + version = "2" + } +} +`, rInt, location, storageSuffix, batchAccountSuffix) } From f6dd46b42131dfab84d7dc6040ef8bd445f68318 Mon Sep 17 00:00:00 2001 From: Julien Corioland Date: Tue, 4 Dec 2018 14:51:16 +0100 Subject: [PATCH 05/13] Datasource for Azure Batch account --- azurerm/data_source_batch_account.go | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/azurerm/data_source_batch_account.go b/azurerm/data_source_batch_account.go index d7312df7e607..34d11db0b2ad 100644 --- a/azurerm/data_source_batch_account.go +++ b/azurerm/data_source_batch_account.go @@ -3,10 +3,7 @@ package azurerm import ( "fmt" - "github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch" - "github.com/hashicorp/terraform/helper/schema" - "github.com/hashicorp/terraform/helper/validation" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -28,14 +25,9 @@ func dataSourceArmBatchAccount() *schema.Resource { Computed: true, }, "pool_allocation_mode": { - Type: schema.TypeString, - Optional: true, - Default: string(batch.BatchService), - DiffSuppressFunc: ignoreCaseDiffSuppressFunc, - ValidateFunc: validation.StringInSlice([]string{ - string(batch.BatchService), - string(batch.UserSubscription), - }, true), + Type: schema.TypeString, + Optional: true, + Computed: true, }, "tags": tagsForDataSourceSchema(), }, @@ -58,16 +50,21 @@ func dataSourceArmBatchAccountRead(d *schema.ResourceData, meta interface{}) err return fmt.Errorf("Error making Read request on AzureRM Batch account %q: %+v", name, err) } - // todo : fetch properties - d.SetId(*resp.ID) d.Set("name", name) d.Set("resource_group_name", resourceGroup) + if location := resp.Location; location != nil { d.Set("location", azureRMNormalizeLocation(*location)) } + if autoStorage := resp.AutoStorage; autoStorage != nil { + d.Set("storage_account_id", autoStorage.StorageAccountID) + } + + d.Set("pool_allocation_mode", resp.PoolAllocationMode) + flattenAndSetTags(d, resp.Tags) return nil From ec101b5b2a55fe4c4eddcdd477b05267d6d05a99 Mon Sep 17 00:00:00 2001 From: Julien Corioland Date: Wed, 5 Dec 2018 17:54:01 +0100 Subject: [PATCH 06/13] fix Batch account delete function --- azurerm/resource_arm_batch_account.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/azurerm/resource_arm_batch_account.go b/azurerm/resource_arm_batch_account.go index ca31a103df6a..0c6b6c456c37 100644 --- a/azurerm/resource_arm_batch_account.go +++ b/azurerm/resource_arm_batch_account.go @@ -3,6 +3,7 @@ package azurerm import ( "fmt" "log" + "net/http" "regexp" "github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch" @@ -193,7 +194,8 @@ func resourceArmBatchAccountDelete(d *schema.ResourceData, meta interface{}) err } err = future.WaitForCompletionRef(ctx, client.Client) - if err != nil { + // if the error is not that the Batch account was not found + if err != nil && future.Response().StatusCode != http.StatusNotFound { return fmt.Errorf("Error waiting for deletion of Batch account %q (Resource Group %q): %+v", name, resourceGroupName, err) } From 3f1d55c3eeccce432b0abf6ab7c7f45527ddc563 Mon Sep 17 00:00:00 2001 From: Julien Corioland Date: Mon, 10 Dec 2018 10:37:00 +0100 Subject: [PATCH 07/13] fix batch account create with no storage id --- azurerm/resource_arm_batch_account.go | 9 +++-- azurerm/resource_arm_batch_account_test.go | 47 ++++++++++++++++++++++ 2 files changed, 53 insertions(+), 3 deletions(-) diff --git a/azurerm/resource_arm_batch_account.go b/azurerm/resource_arm_batch_account.go index 0c6b6c456c37..fd66b62f4918 100644 --- a/azurerm/resource_arm_batch_account.go +++ b/azurerm/resource_arm_batch_account.go @@ -67,14 +67,17 @@ func resourceArmBatchAccountCreate(d *schema.ResourceData, meta interface{}) err parameters := batch.AccountCreateParameters{ Location: &location, AccountCreateProperties: &batch.AccountCreateProperties{ - AutoStorage: &batch.AutoStorageBaseProperties{ - StorageAccountID: &storageAccountId, - }, PoolAllocationMode: batch.PoolAllocationMode(poolAllocationMode), }, Tags: expandTags(tags), } + if storageAccountId != "" { + parameters.AccountCreateProperties.AutoStorage = &batch.AutoStorageBaseProperties{ + StorageAccountID: &storageAccountId, + } + } + future, err := client.Create(ctx, resourceGroupName, name, parameters) if err != nil { return fmt.Errorf("Error creating Batch account %q (Resource Group %q): %+v", name, resourceGroupName, err) diff --git a/azurerm/resource_arm_batch_account_test.go b/azurerm/resource_arm_batch_account_test.go index 94cc1d3b3859..9ee96770bb05 100644 --- a/azurerm/resource_arm_batch_account_test.go +++ b/azurerm/resource_arm_batch_account_test.go @@ -73,6 +73,33 @@ func TestAccAzureRMBatchAccount_basic(t *testing.T) { }) } +func TestAccAzureRMBatchAccount_noStorageAccount(t *testing.T) { + resourceName := "azurerm_batch_account.test" + ri := acctest.RandInt() + rs := acctest.RandString(4) + location := testLocation() + + config := testAccAzureRMBatchAccount_noStorageAccount(ri, rs, location) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMBatchAccountDestroy, + Steps: []resource.TestStep{ + // Create + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMBatchAccountExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "pool_allocation_mode", "BatchService"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.env", "test"), + ), + }, + }, + }) +} + func testCheckAzureRMBatchAccountExists(name string) resource.TestCheckFunc { return func(s *terraform.State) error { // Ensure we have enough information in state to look up in API @@ -184,3 +211,23 @@ resource "azurerm_batch_account" "test" { } `, rInt, location, storageSuffix, batchAccountSuffix) } + +func testAccAzureRMBatchAccount_noStorageAccount(rInt int, batchAccountSuffix string, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "testaccbatch%d" + location = "%s" +} + +resource "azurerm_batch_account" "test" { + name = "testaccbatch%s" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + pool_allocation_mode = "BatchService" + + tags { + env = "test" + } +} +`, rInt, location, batchAccountSuffix) +} From bf5a19c5d2476633794852353a39650a25547e64 Mon Sep 17 00:00:00 2001 From: Julien Corioland Date: Mon, 10 Dec 2018 10:40:42 +0100 Subject: [PATCH 08/13] docs for batch account --- website/docs/d/batch_account.html.markdown | 47 ++++++++++++++ website/docs/r/batch_account.html.markdown | 73 ++++++++++++++++++++++ 2 files changed, 120 insertions(+) create mode 100644 website/docs/d/batch_account.html.markdown create mode 100644 website/docs/r/batch_account.html.markdown diff --git a/website/docs/d/batch_account.html.markdown b/website/docs/d/batch_account.html.markdown new file mode 100644 index 000000000000..d6cb3cc12ded --- /dev/null +++ b/website/docs/d/batch_account.html.markdown @@ -0,0 +1,47 @@ +--- +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_batch_account" +sidebar_current: "docs-azurerm-datasource-batch-account" +description: |- + Get information about an existing Batch Account + +--- + +# Data Source: azurerm_batch_account + +Use this data source to access information about an existing Batch Account. + +## Example Usage + +```hcl +data "azurerm_batch_account "test" { + name = "testbatchaccount" + resource_group_name = "test" +} + +output "login_server" { + value = "${data.azurerm_batch_account.test.pool_allocation_mode}" +} +``` + +## Argument Reference + +* `name` - (Required) The name of the Batch account. + +* `resource_group_name` - (Required) The Name of the Resource Group where this Batch account exists. + +## Attributes Reference + +The following attributes are exported: + +* `id` - The Batch account ID. + +* `name` - The Batch account name. + +* `location` - The Azure Region in which this Batch account exists. + +* `pool_allocation_mode` - The pool allocation mode configured for this Batch account. + +* `storage_account_id` - The ID of the Storage Account used for this Batch account. + +* `tags` - A map of tags assigned to the Batch account. diff --git a/website/docs/r/batch_account.html.markdown b/website/docs/r/batch_account.html.markdown new file mode 100644 index 000000000000..cc252dc0c2f2 --- /dev/null +++ b/website/docs/r/batch_account.html.markdown @@ -0,0 +1,73 @@ +--- +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_batch_account" +sidebar_current: "docs-azurerm-resource-batch-account" +description: |- + Manages an Azure Batch account. + +--- + +# azurerm_batch_account + +Manages an Azure Batch account. + +## Example Usage + +```hcl +resource "azurerm_resource_group" "test" { + name = "testbatch" + location = "westeurope" +} + +resource "azurerm_storage_account" "test" { + name = "teststorage" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + account_tier = "Standard" + account_replication_type = "LRS" + } + +resource "azurerm_batch_account" "test" { + name = "testbatchaccount" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + pool_allocation_mode = "BatchService" + storage_account_id = "${azurerm_storage_account.test.id}" + + tags { + env = "test" + } +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) Specifies the name of the Batch account. Changing this forces a new resource to be created. + +* `resource_group_name` - (Required) The name of the resource group in which to create the Batch account. Changing this forces a new resource to be created. + +* `location` - (Required) Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created. + +* `pool_allocation_mode` - (Optional) Specifies the mode to use for pool allocation: BatchService (default) or UserSubscription. + +* `storage_account_id` - (Optional) Specifies the storage account to use for the Batch account. If not specified, Azure Batch will manage the storage. + +* `tags` - (Optional) A mapping of tags to assign to the resource. + +## Attributes Reference + +The following attributes are exported: + +* `id` - The Batch account ID. + +* `name` - The Batch account name. + +* `location` - The Azure Region in which this Batch account exists. + +* `pool_allocation_mode` - The pool allocation mode configured for this Batch account. + +* `storage_account_id` - The ID of the Storage Account used for this Batch account. + +* `tags` - A map of tags assigned to the Batch account. From f2a98a189af483e2678d05805fd23fbd8bc28174 Mon Sep 17 00:00:00 2001 From: Julien Corioland Date: Wed, 12 Dec 2018 12:27:19 +0100 Subject: [PATCH 09/13] batch account fixes after review --- azurerm/data_source_batch_account.go | 12 ++++++------ azurerm/resource_arm_batch_account.go | 21 ++++++++++++++------- website/docs/d/batch_account.html.markdown | 2 +- website/docs/r/batch_account.html.markdown | 12 +----------- 4 files changed, 22 insertions(+), 25 deletions(-) diff --git a/azurerm/data_source_batch_account.go b/azurerm/data_source_batch_account.go index 34d11db0b2ad..2b2e738e66bd 100644 --- a/azurerm/data_source_batch_account.go +++ b/azurerm/data_source_batch_account.go @@ -18,7 +18,7 @@ func dataSourceArmBatchAccount() *schema.Resource { ForceNew: true, ValidateFunc: validateAzureRMBatchAccountName, }, - "resource_group_name": resourceGroupNameDiffSuppressSchema(), + "resource_group_name": resourceGroupNameForDataSourceSchema(), "location": locationForDataSourceSchema(), "storage_account_id": { Type: schema.TypeString, @@ -26,7 +26,6 @@ func dataSourceArmBatchAccount() *schema.Resource { }, "pool_allocation_mode": { Type: schema.TypeString, - Optional: true, Computed: true, }, "tags": tagsForDataSourceSchema(), @@ -59,12 +58,13 @@ func dataSourceArmBatchAccountRead(d *schema.ResourceData, meta interface{}) err d.Set("location", azureRMNormalizeLocation(*location)) } - if autoStorage := resp.AutoStorage; autoStorage != nil { - d.Set("storage_account_id", autoStorage.StorageAccountID) + if props := resp.AccountProperties; props != nil { + if autoStorage := props.AutoStorage; autoStorage != nil { + d.Set("storage_account_id", autoStorage.StorageAccountID) + } + d.Set("pool_allocation_mode", props.PoolAllocationMode) } - d.Set("pool_allocation_mode", resp.PoolAllocationMode) - flattenAndSetTags(d, resp.Tags) return nil diff --git a/azurerm/resource_arm_batch_account.go b/azurerm/resource_arm_batch_account.go index fd66b62f4918..31771460550c 100644 --- a/azurerm/resource_arm_batch_account.go +++ b/azurerm/resource_arm_batch_account.go @@ -30,11 +30,12 @@ func resourceArmBatchAccount() *schema.Resource { ForceNew: true, ValidateFunc: validateAzureRMBatchAccountName, }, - "resource_group_name": resourceGroupNameDiffSuppressSchema(), + "resource_group_name": resourceGroupNameSchema(), "location": locationSchema(), "storage_account_id": { Type: schema.TypeString, Optional: true, + Computed: true, ValidateFunc: azure.ValidateResourceIDOrEmpty, }, "pool_allocation_mode": { @@ -125,14 +126,16 @@ func resourceArmBatchAccountRead(d *schema.ResourceData, meta interface{}) error d.Set("name", resp.Name) d.Set("resource_group_name", resourceGroupName) - d.Set("pool_allocation_mode", resp.PoolAllocationMode) if location := resp.Location; location != nil { d.Set("location", azureRMNormalizeLocation(*location)) } - if resp.AutoStorage != nil { - d.Set("storage_acount_id", resp.AutoStorage.StorageAccountID) + if props := resp.AccountProperties; props != nil { + if autoStorage := props.AutoStorage; autoStorage != nil { + d.Set("storage_account_id", autoStorage.StorageAccountID) + } + d.Set("pool_allocation_mode", props.PoolAllocationMode) } flattenAndSetTags(d, resp.Tags) @@ -146,8 +149,12 @@ func resourceArmBatchAccountUpdate(d *schema.ResourceData, meta interface{}) err log.Printf("[INFO] preparing arguments for Azure Batch account update.") - resourceGroupName := d.Get("resource_group_name").(string) - name := d.Get("name").(string) + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + name := id.Path["batchAccounts"] + resourceGroupName := id.ResourceGroup storageAccountId := d.Get("storage_account_id").(string) tags := d.Get("tags").(map[string]interface{}) @@ -161,7 +168,7 @@ func resourceArmBatchAccountUpdate(d *schema.ResourceData, meta interface{}) err Tags: expandTags(tags), } - _, err := client.Update(ctx, resourceGroupName, name, parameters) + _, err = client.Update(ctx, resourceGroupName, name, parameters) if err != nil { return fmt.Errorf("Error updating Batch account %q (Resource Group %q): %+v", name, resourceGroupName, err) } diff --git a/website/docs/d/batch_account.html.markdown b/website/docs/d/batch_account.html.markdown index d6cb3cc12ded..23eb9df8d1f6 100644 --- a/website/docs/d/batch_account.html.markdown +++ b/website/docs/d/batch_account.html.markdown @@ -19,7 +19,7 @@ data "azurerm_batch_account "test" { resource_group_name = "test" } -output "login_server" { +output "pool_allocation_mode" { value = "${data.azurerm_batch_account.test.pool_allocation_mode}" } ``` diff --git a/website/docs/r/batch_account.html.markdown b/website/docs/r/batch_account.html.markdown index cc252dc0c2f2..a9fc3e7b0359 100644 --- a/website/docs/r/batch_account.html.markdown +++ b/website/docs/r/batch_account.html.markdown @@ -50,7 +50,7 @@ The following arguments are supported: * `location` - (Required) Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created. -* `pool_allocation_mode` - (Optional) Specifies the mode to use for pool allocation: BatchService (default) or UserSubscription. +* `pool_allocation_mode` - (Optional) Specifies the mode to use for pool allocation. Possible values are `BatchService` or `UserSubscription`. Defaults to `BatchService`. * `storage_account_id` - (Optional) Specifies the storage account to use for the Batch account. If not specified, Azure Batch will manage the storage. @@ -61,13 +61,3 @@ The following arguments are supported: The following attributes are exported: * `id` - The Batch account ID. - -* `name` - The Batch account name. - -* `location` - The Azure Region in which this Batch account exists. - -* `pool_allocation_mode` - The pool allocation mode configured for this Batch account. - -* `storage_account_id` - The ID of the Storage Account used for this Batch account. - -* `tags` - A map of tags assigned to the Batch account. From 5004ccc43403301204659d95b5334ade0c005b11 Mon Sep 17 00:00:00 2001 From: Julien Corioland Date: Thu, 13 Dec 2018 09:40:35 +0100 Subject: [PATCH 10/13] update examples + docs for Batch account --- examples/batch/README.md | 3 +-- examples/batch/main.tf | 14 +++++--------- examples/batch/variables.tf | 20 -------------------- website/docs/r/batch_account.html.markdown | 4 ++++ 4 files changed, 10 insertions(+), 31 deletions(-) diff --git a/examples/batch/README.md b/examples/batch/README.md index deb0f4d3f877..5e0969cb1c5a 100644 --- a/examples/batch/README.md +++ b/examples/batch/README.md @@ -1,13 +1,12 @@ # Azure Batch Sample -Sample to deploy a Job in Azure Batch +Sample to deploy an Azure Batch instance ## Creates 1. A Resource Group 2. A [Storage Account](https://docs.microsoft.com/en-us/azure/batch/batch-api-basics#azure-storage-account) 3. A [Batch Account](https://docs.microsoft.com/en-us/azure/batch/batch-api-basics#account) -4. A [Pool](https://docs.microsoft.com/en-us/azure/batch/batch-api-basics#pool) of compute nodes ## Usage diff --git a/examples/batch/main.tf b/examples/batch/main.tf index 2e760e14ffe1..51beb14e758c 100644 --- a/examples/batch/main.tf +++ b/examples/batch/main.tf @@ -1,6 +1,10 @@ # Configure the Microsoft Azure Provider provider "azurerm" { - # if you're using a Service Principal (shared account) then either set the environment variables, or fill these in: # subscription_id = "..." # client_id = "..." # client_secret = "..." # tenant_id = "..." + # if you're using a Service Principal (shared account) then either set the environment variables, or fill these in: + # subscription_id = "..." + # client_id = "..." + # client_secret = "..." + # tenant_id = "..." } resource "azurerm_resource_group" "rg" { @@ -26,12 +30,4 @@ resource "azurerm_batch_account" "batch" { resource_group_name = "${azurerm_resource_group.rg.name}" location = "${azurerm_resource_group.rg.location}" storage_account_name = "${azurerm_storage_account.stor.name}" -} - -resource "azurerm_batch_pool" "pool" { - id = "pool${random_integer.ri.result}" - vm_size = "${var.batch_pool_nodes_vm_size}" - target_dedicated_node = "${var.batch_pool_nodes_count}" - vm_image = "${var.batch_pool_nodes_vm_image}" - node_agent_sku_id = "${var.batch.pool_nodes_agent_sku_id}" } \ No newline at end of file diff --git a/examples/batch/variables.tf b/examples/batch/variables.tf index 93343cdf49a5..3c2d849e680b 100644 --- a/examples/batch/variables.tf +++ b/examples/batch/variables.tf @@ -20,25 +20,5 @@ variable "storage_replication_type" { default = "LRS" } -variable "batch_pool_nodes_vm_size" { - description = "Size of the virtual machines in the nodes pool" - default = "Standard_A1_v2" -} - -variable "batch_pool_nodes_count" { - description = "Number of virtual machines in the nodes pool" - default = 2 -} - -variable "batch_pool_nodes_vm_image" { - description = "Virtual machine image to use for the nodes in the pool" - default = "canonical:ubuntuserver:16.04-LTS" -} - -variable "batch_pool_nodes_agent_sku_id" { - description = "Agent Sku to use for the nodes in the pool" - default = "batch.node.ubuntu 16.04" -} - diff --git a/website/docs/r/batch_account.html.markdown b/website/docs/r/batch_account.html.markdown index a9fc3e7b0359..d6abe978bda4 100644 --- a/website/docs/r/batch_account.html.markdown +++ b/website/docs/r/batch_account.html.markdown @@ -61,3 +61,7 @@ The following arguments are supported: The following attributes are exported: * `id` - The Batch account ID. + +* `pool_allocation_mode` - (Optional) Specifies the mode to use for pool allocation. Possible values are `BatchService` or `UserSubscription`. Defaults to `BatchService`. + +* `storage_account_id` - (Optional) Specifies the storage account to use for the Batch account. If not specified, Azure Batch will manage the storage. From 8d40fb442bc2d474514c149256912a0c22b3476c Mon Sep 17 00:00:00 2001 From: Julien Corioland Date: Thu, 13 Dec 2018 09:41:05 +0100 Subject: [PATCH 11/13] update Batch account after review --- azurerm/data_source_batch_account_test.go | 86 +++++++++++++++++++--- azurerm/resource_arm_batch_account.go | 19 ++--- azurerm/resource_arm_batch_account_test.go | 38 ++++------ 3 files changed, 98 insertions(+), 45 deletions(-) diff --git a/azurerm/data_source_batch_account_test.go b/azurerm/data_source_batch_account_test.go index 2f97cbeda897..04e71dc9053f 100644 --- a/azurerm/data_source_batch_account_test.go +++ b/azurerm/data_source_batch_account_test.go @@ -11,9 +11,9 @@ import ( func TestAccDataSourceAzureRMBatchAccount_basic(t *testing.T) { dataSourceName := "data.azurerm_batch_account.test" ri := acctest.RandInt() - name := fmt.Sprintf("acctestbatchaccount%d", ri) + rs := acctest.RandString(4) location := testLocation() - config := testAccDataSourceAzureRMBatchAccount_basic(name, location) + config := testAccDataSourceAzureRMBatchAccount_basic(ri, rs, location) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -22,8 +22,32 @@ func TestAccDataSourceAzureRMBatchAccount_basic(t *testing.T) { { Config: config, Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(dataSourceName, "name", name), + resource.TestCheckResourceAttr(dataSourceName, "name", fmt.Sprintf("testaccbatch%s", rs)), resource.TestCheckResourceAttr(dataSourceName, "location", azureRMNormalizeLocation(location)), + resource.TestCheckResourceAttr(dataSourceName, "pool_allocation_mode", "BatchService"), + ), + }, + }, + }) +} + +func TestAccDataSourceAzureRMBatchAccount_complete(t *testing.T) { + dataSourceName := "data.azurerm_batch_account.test" + ri := acctest.RandInt() + rs := acctest.RandString(4) + location := testLocation() + config := testAccDataSourceAzureRMBatchAccount_complete(ri, rs, location) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(dataSourceName, "name", fmt.Sprintf("testaccbatch%s", rs)), + resource.TestCheckResourceAttr(dataSourceName, "location", azureRMNormalizeLocation(location)), + resource.TestCheckResourceAttr(dataSourceName, "pool_allocation_mode", "BatchService"), resource.TestCheckResourceAttr(dataSourceName, "tags.%", "1"), resource.TestCheckResourceAttr(dataSourceName, "tags.env", "test"), ), @@ -32,19 +56,57 @@ func TestAccDataSourceAzureRMBatchAccount_basic(t *testing.T) { }) } -func testAccDataSourceAzureRMBatchAccount_basic(name string, location string) string { +func testAccDataSourceAzureRMBatchAccount_basic(rInt int, rString string, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "testaccbatch%d" + location = "%s" +} + +resource "azurerm_batch_account" "test" { + name = "testaccbatch%s" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + pool_allocation_mode = "BatchService" +} + +data "azurerm_batch_account" "test" { + name = "${azurerm_batch_account.test.name}" + resource_group_name = "${azurerm_resource_group.test.name}" +} +`, rInt, location, rString) +} + +func testAccDataSourceAzureRMBatchAccount_complete(rInt int, rString string, location string) string { return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "testaccbatch%d" + location = "%s" +} + +resource "azurerm_storage_account" "test" { + name = "testaccsa%s" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + account_tier = "Standard" + account_replication_type = "LRS" + } + resource "azurerm_batch_account" "test" { - name = "%s" - location = "%s" + name = "testaccbatch%s" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + pool_allocation_mode = "BatchService" + storage_account_id = "${azurerm_storage_account.test.id}" - tags { - env = "test" - } + tags { + env = "test" + } } data "azurerm_batch_account" "test" { - name = "${azurerm_batch_account.test.name}" - } -`, name, location) + name = "${azurerm_batch_account.test.name}" + resource_group_name = "${azurerm_resource_group.test.name}" +} +`, rInt, location, rString, rString) } diff --git a/azurerm/resource_arm_batch_account.go b/azurerm/resource_arm_batch_account.go index 31771460550c..84fe8d3c689a 100644 --- a/azurerm/resource_arm_batch_account.go +++ b/azurerm/resource_arm_batch_account.go @@ -3,13 +3,13 @@ package azurerm import ( "fmt" "log" - "net/http" "regexp" "github.com/Azure/azure-sdk-for-go/services/batch/mgmt/2017-09-01/batch" "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/helper/validation" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/response" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) @@ -84,8 +84,7 @@ func resourceArmBatchAccountCreate(d *schema.ResourceData, meta interface{}) err return fmt.Errorf("Error creating Batch account %q (Resource Group %q): %+v", name, resourceGroupName, err) } - err = future.WaitForCompletionRef(ctx, client.Client) - if err != nil { + if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { return fmt.Errorf("Error waiting for creation of Batch account %q (Resource Group %q): %+v", name, resourceGroupName, err) } @@ -168,8 +167,7 @@ func resourceArmBatchAccountUpdate(d *schema.ResourceData, meta interface{}) err Tags: expandTags(tags), } - _, err = client.Update(ctx, resourceGroupName, name, parameters) - if err != nil { + if _, err = client.Update(ctx, resourceGroupName, name, parameters); err != nil { return fmt.Errorf("Error updating Batch account %q (Resource Group %q): %+v", name, resourceGroupName, err) } @@ -203,10 +201,10 @@ func resourceArmBatchAccountDelete(d *schema.ResourceData, meta interface{}) err return fmt.Errorf("Error deleting Batch account %q (Resource Group %q): %+v", name, resourceGroupName, err) } - err = future.WaitForCompletionRef(ctx, client.Client) - // if the error is not that the Batch account was not found - if err != nil && future.Response().StatusCode != http.StatusNotFound { - return fmt.Errorf("Error waiting for deletion of Batch account %q (Resource Group %q): %+v", name, resourceGroupName, err) + if err = future.WaitForCompletionRef(ctx, client.Client); err != nil { + if !response.WasNotFound(future.Response()) { + return fmt.Errorf("Error waiting for deletion of Batch account %q (Resource Group %q): %+v", name, resourceGroupName, err) + } } return nil @@ -215,8 +213,7 @@ func resourceArmBatchAccountDelete(d *schema.ResourceData, meta interface{}) err func validateAzureRMBatchAccountName(v interface{}, k string) (warnings []string, errors []error) { value := v.(string) if !regexp.MustCompile(`^[a-z0-9]+$`).MatchString(value) { - errors = append(errors, fmt.Errorf( - "lowercase letters and numbers only are allowed in %q: %q", k, value)) + errors = append(errors, fmt.Errorf("lowercase letters and numbers only are allowed in %q: %q", k, value)) } if 3 > len(value) { diff --git a/azurerm/resource_arm_batch_account_test.go b/azurerm/resource_arm_batch_account_test.go index 9ee96770bb05..c6fe2f581146 100644 --- a/azurerm/resource_arm_batch_account_test.go +++ b/azurerm/resource_arm_batch_account_test.go @@ -30,25 +30,27 @@ func TestValidateBatchAccountName(t *testing.T) { if test.shouldError && len(es) == 0 { t.Fatalf("Expected validating name %q to fail", test.input) } + + if !test.shouldError && len(es) > 1 { + t.Fatalf("Expected validating name %q to fail", test.input) + } } } -func TestAccAzureRMBatchAccount_basic(t *testing.T) { +func TestAccAzureRMBatchAccount_complete(t *testing.T) { resourceName := "azurerm_batch_account.test" ri := acctest.RandInt() rs := acctest.RandString(4) - rs2 := acctest.RandString(4) location := testLocation() - config := testAccAzureRMBatchAccount_basic(ri, rs, rs, location) - configUpdate := testAccAzureRMBatchAccount_basicUpdate(ri, rs2, rs, location) + config := testAccAzureRMBatchAccount_complete(ri, rs, location) + configUpdate := testAccAzureRMBatchAccount_completeUpdated(ri, rs, location) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testCheckAzureRMBatchAccountDestroy, Steps: []resource.TestStep{ - // Create { Config: config, Check: resource.ComposeTestCheckFunc( @@ -58,7 +60,6 @@ func TestAccAzureRMBatchAccount_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "tags.env", "test"), ), }, - // Update { Config: configUpdate, Check: resource.ComposeTestCheckFunc( @@ -73,27 +74,24 @@ func TestAccAzureRMBatchAccount_basic(t *testing.T) { }) } -func TestAccAzureRMBatchAccount_noStorageAccount(t *testing.T) { +func TestAccAzureRMBatchAccount_noStorageAccount_basic(t *testing.T) { resourceName := "azurerm_batch_account.test" ri := acctest.RandInt() rs := acctest.RandString(4) location := testLocation() - config := testAccAzureRMBatchAccount_noStorageAccount(ri, rs, location) + config := testAccAzureRMBatchAccount_noStorageAccount_basic(ri, rs, location) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testCheckAzureRMBatchAccountDestroy, Steps: []resource.TestStep{ - // Create { Config: config, Check: resource.ComposeTestCheckFunc( testCheckAzureRMBatchAccountExists(resourceName), resource.TestCheckResourceAttr(resourceName, "pool_allocation_mode", "BatchService"), - resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(resourceName, "tags.env", "test"), ), }, }, @@ -153,7 +151,7 @@ func testCheckAzureRMBatchAccountDestroy(s *terraform.State) error { return nil } -func testAccAzureRMBatchAccount_basic(rInt int, storageSuffix string, batchAccountSuffix string, location string) string { +func testAccAzureRMBatchAccount_complete(rInt int, rString string, location string) string { return fmt.Sprintf(` resource "azurerm_resource_group" "test" { name = "testaccbatch%d" @@ -179,10 +177,10 @@ resource "azurerm_batch_account" "test" { env = "test" } } -`, rInt, location, storageSuffix, batchAccountSuffix) +`, rInt, location, rString, rString) } -func testAccAzureRMBatchAccount_basicUpdate(rInt int, storageSuffix string, batchAccountSuffix string, location string) string { +func testAccAzureRMBatchAccount_completeUpdated(rInt int, rString string, location string) string { return fmt.Sprintf(` resource "azurerm_resource_group" "test" { name = "testaccbatch%d" @@ -190,7 +188,7 @@ resource "azurerm_resource_group" "test" { } resource "azurerm_storage_account" "test" { - name = "testaccsa%s" + name = "testaccsa%s2" resource_group_name = "${azurerm_resource_group.test.name}" location = "${azurerm_resource_group.test.location}" account_tier = "Standard" @@ -205,14 +203,14 @@ resource "azurerm_batch_account" "test" { storage_account_id = "${azurerm_storage_account.test.id}" tags { - env = "test" + env = "test" version = "2" } } -`, rInt, location, storageSuffix, batchAccountSuffix) +`, rInt, location, rString, rString) } -func testAccAzureRMBatchAccount_noStorageAccount(rInt int, batchAccountSuffix string, location string) string { +func testAccAzureRMBatchAccount_noStorageAccount_basic(rInt int, batchAccountSuffix string, location string) string { return fmt.Sprintf(` resource "azurerm_resource_group" "test" { name = "testaccbatch%d" @@ -224,10 +222,6 @@ resource "azurerm_batch_account" "test" { resource_group_name = "${azurerm_resource_group.test.name}" location = "${azurerm_resource_group.test.location}" pool_allocation_mode = "BatchService" - - tags { - env = "test" - } } `, rInt, location, batchAccountSuffix) } From 00d8020a426beae7457cae2a62aa0c43e027f327 Mon Sep 17 00:00:00 2001 From: Julien Corioland Date: Fri, 14 Dec 2018 09:46:13 +0100 Subject: [PATCH 12/13] fix indent in test data --- azurerm/data_source_batch_account_test.go | 4 +- azurerm/resource_arm_batch_account_test.go | 60 +++++++++++----------- 2 files changed, 32 insertions(+), 32 deletions(-) diff --git a/azurerm/data_source_batch_account_test.go b/azurerm/data_source_batch_account_test.go index 04e71dc9053f..b168d456865d 100644 --- a/azurerm/data_source_batch_account_test.go +++ b/azurerm/data_source_batch_account_test.go @@ -64,7 +64,7 @@ resource "azurerm_resource_group" "test" { } resource "azurerm_batch_account" "test" { - name = "testaccbatch%s" + name = "testaccbatch%s" resource_group_name = "${azurerm_resource_group.test.name}" location = "${azurerm_resource_group.test.location}" pool_allocation_mode = "BatchService" @@ -90,7 +90,7 @@ resource "azurerm_storage_account" "test" { location = "${azurerm_resource_group.test.location}" account_tier = "Standard" account_replication_type = "LRS" - } +} resource "azurerm_batch_account" "test" { name = "testaccbatch%s" diff --git a/azurerm/resource_arm_batch_account_test.go b/azurerm/resource_arm_batch_account_test.go index c6fe2f581146..661328cb9109 100644 --- a/azurerm/resource_arm_batch_account_test.go +++ b/azurerm/resource_arm_batch_account_test.go @@ -154,8 +154,8 @@ func testCheckAzureRMBatchAccountDestroy(s *terraform.State) error { func testAccAzureRMBatchAccount_complete(rInt int, rString string, location string) string { return fmt.Sprintf(` resource "azurerm_resource_group" "test" { - name = "testaccbatch%d" - location = "%s" + name = "testaccbatch%d" + location = "%s" } resource "azurerm_storage_account" "test" { @@ -167,15 +167,15 @@ resource "azurerm_storage_account" "test" { } resource "azurerm_batch_account" "test" { - name = "testaccbatch%s" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - pool_allocation_mode = "BatchService" - storage_account_id = "${azurerm_storage_account.test.id}" - - tags { - env = "test" - } + name = "testaccbatch%s" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + pool_allocation_mode = "BatchService" + storage_account_id = "${azurerm_storage_account.test.id}" + + tags { + env = "test" + } } `, rInt, location, rString, rString) } @@ -183,8 +183,8 @@ resource "azurerm_batch_account" "test" { func testAccAzureRMBatchAccount_completeUpdated(rInt int, rString string, location string) string { return fmt.Sprintf(` resource "azurerm_resource_group" "test" { - name = "testaccbatch%d" - location = "%s" + name = "testaccbatch%d" + location = "%s" } resource "azurerm_storage_account" "test" { @@ -193,19 +193,19 @@ resource "azurerm_storage_account" "test" { location = "${azurerm_resource_group.test.location}" account_tier = "Standard" account_replication_type = "LRS" - } +} resource "azurerm_batch_account" "test" { - name = "testaccbatch%s" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - pool_allocation_mode = "BatchService" - storage_account_id = "${azurerm_storage_account.test.id}" - - tags { - env = "test" - version = "2" - } + name = "testaccbatch%s" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + pool_allocation_mode = "BatchService" + storage_account_id = "${azurerm_storage_account.test.id}" + + tags { + env = "test" + version = "2" + } } `, rInt, location, rString, rString) } @@ -213,15 +213,15 @@ resource "azurerm_batch_account" "test" { func testAccAzureRMBatchAccount_noStorageAccount_basic(rInt int, batchAccountSuffix string, location string) string { return fmt.Sprintf(` resource "azurerm_resource_group" "test" { - name = "testaccbatch%d" - location = "%s" + name = "testaccbatch%d" + location = "%s" } resource "azurerm_batch_account" "test" { - name = "testaccbatch%s" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - pool_allocation_mode = "BatchService" + name = "testaccbatch%s" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + pool_allocation_mode = "BatchService" } `, rInt, location, batchAccountSuffix) } From 644c45a4c00d0ad6fa98a4c9ecc83b1f6269e60b Mon Sep 17 00:00:00 2001 From: tombuildsstuff Date: Fri, 14 Dec 2018 10:29:59 +0000 Subject: [PATCH 13/13] fixing comments from the pr --- azurerm/resource_arm_batch_account_test.go | 66 +++++++++++----------- website/docs/r/batch_account.html.markdown | 4 -- 2 files changed, 33 insertions(+), 37 deletions(-) diff --git a/azurerm/resource_arm_batch_account_test.go b/azurerm/resource_arm_batch_account_test.go index 661328cb9109..78b8a1d56409 100644 --- a/azurerm/resource_arm_batch_account_test.go +++ b/azurerm/resource_arm_batch_account_test.go @@ -37,14 +37,13 @@ func TestValidateBatchAccountName(t *testing.T) { } } -func TestAccAzureRMBatchAccount_complete(t *testing.T) { +func TestAccAzureRMBatchAccount_basic(t *testing.T) { resourceName := "azurerm_batch_account.test" ri := acctest.RandInt() rs := acctest.RandString(4) location := testLocation() - config := testAccAzureRMBatchAccount_complete(ri, rs, location) - configUpdate := testAccAzureRMBatchAccount_completeUpdated(ri, rs, location) + config := testAccAzureRMBatchAccount_basic(ri, rs, location) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -56,31 +55,20 @@ func TestAccAzureRMBatchAccount_complete(t *testing.T) { Check: resource.ComposeTestCheckFunc( testCheckAzureRMBatchAccountExists(resourceName), resource.TestCheckResourceAttr(resourceName, "pool_allocation_mode", "BatchService"), - resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(resourceName, "tags.env", "test"), - ), - }, - { - Config: configUpdate, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMBatchAccountExists(resourceName), - resource.TestCheckResourceAttr(resourceName, "pool_allocation_mode", "BatchService"), - resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), - resource.TestCheckResourceAttr(resourceName, "tags.env", "test"), - resource.TestCheckResourceAttr(resourceName, "tags.version", "2"), ), }, }, }) } -func TestAccAzureRMBatchAccount_noStorageAccount_basic(t *testing.T) { +func TestAccAzureRMBatchAccount_complete(t *testing.T) { resourceName := "azurerm_batch_account.test" ri := acctest.RandInt() rs := acctest.RandString(4) location := testLocation() - config := testAccAzureRMBatchAccount_noStorageAccount_basic(ri, rs, location) + config := testAccAzureRMBatchAccount_complete(ri, rs, location) + configUpdate := testAccAzureRMBatchAccount_completeUpdated(ri, rs, location) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -92,6 +80,18 @@ func TestAccAzureRMBatchAccount_noStorageAccount_basic(t *testing.T) { Check: resource.ComposeTestCheckFunc( testCheckAzureRMBatchAccountExists(resourceName), resource.TestCheckResourceAttr(resourceName, "pool_allocation_mode", "BatchService"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.env", "test"), + ), + }, + { + Config: configUpdate, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMBatchAccountExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "pool_allocation_mode", "BatchService"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.env", "test"), + resource.TestCheckResourceAttr(resourceName, "tags.version", "2"), ), }, }, @@ -151,6 +151,22 @@ func testCheckAzureRMBatchAccountDestroy(s *terraform.State) error { return nil } +func testAccAzureRMBatchAccount_basic(rInt int, batchAccountSuffix string, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "testaccbatch%d" + location = "%s" +} + +resource "azurerm_batch_account" "test" { + name = "testaccbatch%s" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "${azurerm_resource_group.test.location}" + pool_allocation_mode = "BatchService" +} +`, rInt, location, batchAccountSuffix) +} + func testAccAzureRMBatchAccount_complete(rInt int, rString string, location string) string { return fmt.Sprintf(` resource "azurerm_resource_group" "test" { @@ -209,19 +225,3 @@ resource "azurerm_batch_account" "test" { } `, rInt, location, rString, rString) } - -func testAccAzureRMBatchAccount_noStorageAccount_basic(rInt int, batchAccountSuffix string, location string) string { - return fmt.Sprintf(` -resource "azurerm_resource_group" "test" { - name = "testaccbatch%d" - location = "%s" -} - -resource "azurerm_batch_account" "test" { - name = "testaccbatch%s" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "${azurerm_resource_group.test.location}" - pool_allocation_mode = "BatchService" -} -`, rInt, location, batchAccountSuffix) -} diff --git a/website/docs/r/batch_account.html.markdown b/website/docs/r/batch_account.html.markdown index d6abe978bda4..a9fc3e7b0359 100644 --- a/website/docs/r/batch_account.html.markdown +++ b/website/docs/r/batch_account.html.markdown @@ -61,7 +61,3 @@ The following arguments are supported: The following attributes are exported: * `id` - The Batch account ID. - -* `pool_allocation_mode` - (Optional) Specifies the mode to use for pool allocation. Possible values are `BatchService` or `UserSubscription`. Defaults to `BatchService`. - -* `storage_account_id` - (Optional) Specifies the storage account to use for the Batch account. If not specified, Azure Batch will manage the storage.