From a669cd30fa80385c01bc40317806127283111e50 Mon Sep 17 00:00:00 2001 From: James Nugent Date: Wed, 1 Jun 2016 14:48:31 -0500 Subject: [PATCH 01/17] deps: Update Azure SDK for Go --- Godeps/Godeps.json | 115 +++--- .../Azure/go-autorest/autorest/azure/azure.go | 72 ---- .../Azure/go-autorest/autorest/client.go | 288 -------------- .../Azure/go-autorest/autorest/error.go | 114 ------ .../golang.org/x/crypto/pkcs12/bmp-string.go | 50 --- .../src/golang.org/x/crypto/pkcs12/crypto.go | 131 ------- .../src/golang.org/x/crypto/pkcs12/errors.go | 23 -- .../x/crypto/pkcs12/internal/rc2/rc2.go | 274 -------------- .../src/golang.org/x/crypto/pkcs12/mac.go | 45 --- .../src/golang.org/x/crypto/pkcs12/pbkdf.go | 170 --------- .../src/golang.org/x/crypto/pkcs12/pkcs12.go | 342 ----------------- .../golang.org/x/crypto/pkcs12/safebags.go | 57 --- .../Azure/azure-sdk-for-go/arm/cdn/client.go | 16 +- .../azure-sdk-for-go/arm/cdn/customdomains.go | 104 +++--- .../azure-sdk-for-go/arm/cdn/endpoints.go | 207 ++++++----- .../Azure/azure-sdk-for-go/arm/cdn/models.go | 29 +- .../arm/cdn/nameavailability.go | 17 +- .../azure-sdk-for-go/arm/cdn/operations.go | 17 +- .../Azure/azure-sdk-for-go/arm/cdn/origins.go | 104 +++--- .../azure-sdk-for-go/arm/cdn/profiles.go | 168 ++++++--- .../Azure/azure-sdk-for-go/arm/cdn/version.go | 10 +- .../arm/compute/availabilitysets.go | 81 ++-- .../azure-sdk-for-go/arm/compute/client.go | 10 +- .../azure-sdk-for-go/arm/compute/models.go | 64 ++-- .../arm/compute/usageoperations.go | 25 +- .../azure-sdk-for-go/arm/compute/version.go | 10 +- .../compute/virtualmachineextensionimages.go | 47 +-- .../arm/compute/virtualmachineextensions.go | 74 ++-- .../arm/compute/virtualmachineimages.go | 75 ++-- .../arm/compute/virtualmachines.go | 277 ++++++++------ .../arm/compute/virtualmachinescalesets.go | 289 +++++++------- .../arm/compute/virtualmachinescalesetvms.go | 172 +++++---- .../arm/compute/virtualmachinesizes.go | 25 +- .../arm/network/applicationgateways.go | 162 ++++---- .../azure-sdk-for-go/arm/network/client.go | 30 +- .../expressroutecircuitauthorizations.go | 94 ++--- .../network/expressroutecircuitpeerings.go | 92 ++--- .../arm/network/expressroutecircuits.go | 172 +++++---- .../network/expressrouteserviceproviders.go | 25 +- .../arm/network/interfaces.go | 164 ++++---- .../arm/network/loadbalancers.go | 114 +++--- .../arm/network/localnetworkgateways.go | 95 ++--- .../azure-sdk-for-go/arm/network/models.go | 84 +++-- .../arm/network/publicipaddresses.go | 118 +++--- .../azure-sdk-for-go/arm/network/routes.go | 92 ++--- .../arm/network/routetables.go | 111 +++--- .../arm/network/securitygroups.go | 113 +++--- .../arm/network/securityrules.go | 93 ++--- .../azure-sdk-for-go/arm/network/subnets.go | 93 ++--- .../azure-sdk-for-go/arm/network/usages.go | 25 +- .../azure-sdk-for-go/arm/network/version.go | 10 +- .../virtualnetworkgatewayconnections.go | 169 +++++---- .../arm/network/virtualnetworkgateways.go | 138 +++---- .../arm/network/virtualnetworks.go | 113 +++--- .../arm/resources/resources/client.go | 105 +++--- .../resources/deploymentoperations.go | 39 +- .../arm/resources/resources/deployments.go | 132 ++++--- .../arm/resources/resources/groups.go | 122 +++--- .../arm/resources/resources/models.go | 8 +- .../resources/resources/policyassignments.go | 157 ++++---- .../resources/resources/policydefinitions.go | 41 +- .../resources/provideroperationdetails.go | 25 +- .../arm/resources/resources/providers.go | 63 ++-- .../arm/resources/resources/resources.go | 100 ++--- .../arm/resources/resources/tags.go | 73 ++-- .../arm/resources/resources/version.go | 12 +- .../azure-sdk-for-go/arm/scheduler/client.go | 7 +- .../arm/scheduler/jobcollections.go | 117 +++--- .../azure-sdk-for-go/arm/scheduler/jobs.go | 109 +++--- .../azure-sdk-for-go/arm/scheduler/models.go | 38 +- .../azure-sdk-for-go/arm/scheduler/version.go | 10 +- .../azure-sdk-for-go/arm/storage/accounts.go | 133 +++---- .../azure-sdk-for-go/arm/storage/client.go | 10 +- .../azure-sdk-for-go/arm/storage/models.go | 10 +- .../arm/storage/usageoperations.go | 17 +- .../azure-sdk-for-go/arm/storage/version.go | 10 +- .../management/publishSettings.go | 2 +- .../management/virtualmachine/client.go | 5 +- .../management/virtualmachine/entities.go | 14 +- .../Azure/azure-sdk-for-go/storage/blob.go | 157 +++++++- .../Azure/azure-sdk-for-go/storage/client.go | 126 ++++++- .../Azure/azure-sdk-for-go/storage/file.go | 1 - .../Azure/azure-sdk-for-go/storage/queue.go | 2 - .../Azure/azure-sdk-for-go/storage/table.go | 129 +++++++ .../storage/table_entities.go | 351 ++++++++++++++++++ vendor/github.com/Azure/go-autorest/LICENSE | 191 ++++++++++ .../go-autorest/autorest/autorest.go | 95 ++--- .../Azure/go-autorest/autorest/azure/async.go | 306 +++++++++++++++ .../Azure/go-autorest/autorest/azure/azure.go | 165 ++++++++ .../go-autorest/autorest/azure/config.go | 13 + .../go-autorest/autorest/azure/devicetoken.go | 193 ++++++++++ .../autorest/azure/environments.go | 111 ++++++ .../go-autorest/autorest/azure/persist.go | 58 +++ .../go-autorest/autorest/azure/token.go | 155 +++++--- .../Azure/go-autorest/autorest/client.go | 190 ++++++++++ .../go-autorest/autorest/date/date.go | 33 +- .../go-autorest/autorest/date/time.go | 46 +-- .../go-autorest/autorest/date/timerfc1123.go | 86 +++++ .../go-autorest/autorest/date/utility.go | 11 + .../Azure/go-autorest/autorest/error.go | 77 ++++ .../go-autorest/autorest/preparer.go | 51 ++- .../go-autorest/autorest/responder.go | 63 +++- .../Azure => }/go-autorest/autorest/sender.go | 115 +++--- .../go-autorest/autorest/to/convert.go | 0 .../go-autorest/autorest/utility.go | 20 + .../go-autorest/autorest/version.go | 6 +- .../dgrijalva/jwt-go/.gitignore | 0 .../dgrijalva/jwt-go/.travis.yml | 0 .../github.com => }/dgrijalva/jwt-go/LICENSE | 0 .../dgrijalva/jwt-go/README.md | 33 +- .../dgrijalva/jwt-go/VERSION_HISTORY.md | 0 .../github.com => }/dgrijalva/jwt-go/doc.go | 0 .../github.com => }/dgrijalva/jwt-go/ecdsa.go | 0 .../dgrijalva/jwt-go/ecdsa_utils.go | 0 .../dgrijalva/jwt-go/errors.go | 0 .../github.com => }/dgrijalva/jwt-go/hmac.go | 0 .../dgrijalva/jwt-go/parser.go | 3 + .../github.com => }/dgrijalva/jwt-go/rsa.go | 0 .../dgrijalva/jwt-go/rsa_pss.go | 0 .../dgrijalva/jwt-go/rsa_utils.go | 0 .../dgrijalva/jwt-go/signing_method.go | 0 .../github.com => }/dgrijalva/jwt-go/token.go | 2 +- 122 files changed, 5481 insertions(+), 4276 deletions(-) delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/azure/azure.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/client.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/error.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/bmp-string.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/crypto.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/errors.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/internal/rc2/rc2.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/mac.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/pbkdf.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/pkcs12.go delete mode 100644 vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/safebags.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/storage/table.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/storage/table_entities.go create mode 100644 vendor/github.com/Azure/go-autorest/LICENSE rename vendor/github.com/Azure/{azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure => }/go-autorest/autorest/autorest.go (53%) create mode 100644 vendor/github.com/Azure/go-autorest/autorest/azure/async.go create mode 100644 vendor/github.com/Azure/go-autorest/autorest/azure/azure.go create mode 100644 vendor/github.com/Azure/go-autorest/autorest/azure/config.go create mode 100644 vendor/github.com/Azure/go-autorest/autorest/azure/devicetoken.go create mode 100644 vendor/github.com/Azure/go-autorest/autorest/azure/environments.go create mode 100644 vendor/github.com/Azure/go-autorest/autorest/azure/persist.go rename vendor/github.com/Azure/{azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure => }/go-autorest/autorest/azure/token.go (62%) create mode 100644 vendor/github.com/Azure/go-autorest/autorest/client.go rename vendor/github.com/Azure/{azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure => }/go-autorest/autorest/date/date.go (82%) rename vendor/github.com/Azure/{azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure => }/go-autorest/autorest/date/time.go (60%) create mode 100644 vendor/github.com/Azure/go-autorest/autorest/date/timerfc1123.go create mode 100644 vendor/github.com/Azure/go-autorest/autorest/date/utility.go create mode 100644 vendor/github.com/Azure/go-autorest/autorest/error.go rename vendor/github.com/Azure/{azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure => }/go-autorest/autorest/preparer.go (86%) rename vendor/github.com/Azure/{azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure => }/go-autorest/autorest/responder.go (76%) rename vendor/github.com/Azure/{azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure => }/go-autorest/autorest/sender.go (70%) rename vendor/github.com/Azure/{azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure => }/go-autorest/autorest/to/convert.go (100%) rename vendor/github.com/Azure/{azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure => }/go-autorest/autorest/utility.go (78%) rename vendor/github.com/Azure/{azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure => }/go-autorest/autorest/version.go (80%) rename vendor/github.com/{Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com => }/dgrijalva/jwt-go/.gitignore (100%) rename vendor/github.com/{Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com => }/dgrijalva/jwt-go/.travis.yml (100%) rename vendor/github.com/{Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com => }/dgrijalva/jwt-go/LICENSE (100%) rename vendor/github.com/{Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com => }/dgrijalva/jwt-go/README.md (60%) rename vendor/github.com/{Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com => }/dgrijalva/jwt-go/VERSION_HISTORY.md (100%) rename vendor/github.com/{Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com => }/dgrijalva/jwt-go/doc.go (100%) rename vendor/github.com/{Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com => }/dgrijalva/jwt-go/ecdsa.go (100%) rename vendor/github.com/{Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com => }/dgrijalva/jwt-go/ecdsa_utils.go (100%) rename vendor/github.com/{Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com => }/dgrijalva/jwt-go/errors.go (100%) rename vendor/github.com/{Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com => }/dgrijalva/jwt-go/hmac.go (100%) rename vendor/github.com/{Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com => }/dgrijalva/jwt-go/parser.go (94%) rename vendor/github.com/{Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com => }/dgrijalva/jwt-go/rsa.go (100%) rename vendor/github.com/{Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com => }/dgrijalva/jwt-go/rsa_pss.go (100%) rename vendor/github.com/{Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com => }/dgrijalva/jwt-go/rsa_utils.go (100%) rename vendor/github.com/{Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com => }/dgrijalva/jwt-go/signing_method.go (100%) rename vendor/github.com/{Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com => }/dgrijalva/jwt-go/token.go (98%) diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json index 156570ab63ff..b36aa48f90d9 100644 --- a/Godeps/Godeps.json +++ b/Godeps/Godeps.json @@ -1,7 +1,7 @@ { "ImportPath": "github.com/hashicorp/terraform", "GoVersion": "go1.6", - "GodepVersion": "v71", + "GodepVersion": "v69", "Packages": [ "./..." ], @@ -43,113 +43,113 @@ }, { "ImportPath": "github.com/Azure/azure-sdk-for-go/arm/cdn", - "Comment": "v1.2-315-g1cb9dff", - "Rev": "1cb9dff8c37b2918ad1ebd7b294d01100a153d27" + "Comment": "v2.1.1-beta-8-gca4d906", + "Rev": "ca4d906d1c0973ae3022588df7dfa13d53b5b476" }, { "ImportPath": "github.com/Azure/azure-sdk-for-go/arm/compute", - "Comment": "v1.2-315-g1cb9dff", - "Rev": "1cb9dff8c37b2918ad1ebd7b294d01100a153d27" + "Comment": "v2.1.1-beta-8-gca4d906", + "Rev": "ca4d906d1c0973ae3022588df7dfa13d53b5b476" }, { "ImportPath": "github.com/Azure/azure-sdk-for-go/arm/network", - "Comment": "v1.2-315-g1cb9dff", - "Rev": "1cb9dff8c37b2918ad1ebd7b294d01100a153d27" + "Comment": "v2.1.1-beta-8-gca4d906", + "Rev": "ca4d906d1c0973ae3022588df7dfa13d53b5b476" }, { "ImportPath": "github.com/Azure/azure-sdk-for-go/arm/resources/resources", - "Comment": "v1.2-315-g1cb9dff", - "Rev": "1cb9dff8c37b2918ad1ebd7b294d01100a153d27" + "Comment": "v2.1.1-beta-8-gca4d906", + "Rev": "ca4d906d1c0973ae3022588df7dfa13d53b5b476" }, { "ImportPath": "github.com/Azure/azure-sdk-for-go/arm/scheduler", - "Comment": "v1.2-315-g1cb9dff", - "Rev": "1cb9dff8c37b2918ad1ebd7b294d01100a153d27" + "Comment": "v2.1.1-beta-8-gca4d906", + "Rev": "ca4d906d1c0973ae3022588df7dfa13d53b5b476" }, { "ImportPath": "github.com/Azure/azure-sdk-for-go/arm/storage", - "Comment": "v1.2-315-g1cb9dff", - "Rev": "1cb9dff8c37b2918ad1ebd7b294d01100a153d27" + "Comment": "v2.1.1-beta-8-gca4d906", + "Rev": "ca4d906d1c0973ae3022588df7dfa13d53b5b476" }, { "ImportPath": "github.com/Azure/azure-sdk-for-go/core/http", - "Comment": "v1.2-315-g1cb9dff", - "Rev": "1cb9dff8c37b2918ad1ebd7b294d01100a153d27" + "Comment": "v2.1.1-beta-8-gca4d906", + "Rev": "ca4d906d1c0973ae3022588df7dfa13d53b5b476" }, { "ImportPath": "github.com/Azure/azure-sdk-for-go/core/tls", - "Comment": "v1.2-315-g1cb9dff", - "Rev": "1cb9dff8c37b2918ad1ebd7b294d01100a153d27" + "Comment": "v2.1.1-beta-8-gca4d906", + "Rev": "ca4d906d1c0973ae3022588df7dfa13d53b5b476" }, { "ImportPath": "github.com/Azure/azure-sdk-for-go/management", - "Comment": "v1.2-315-g1cb9dff", - "Rev": "1cb9dff8c37b2918ad1ebd7b294d01100a153d27" + "Comment": "v2.1.1-beta-8-gca4d906", + "Rev": "ca4d906d1c0973ae3022588df7dfa13d53b5b476" }, { "ImportPath": "github.com/Azure/azure-sdk-for-go/management/affinitygroup", - "Comment": "v1.2-315-g1cb9dff", - "Rev": "1cb9dff8c37b2918ad1ebd7b294d01100a153d27" + "Comment": "v2.1.1-beta-8-gca4d906", + "Rev": "ca4d906d1c0973ae3022588df7dfa13d53b5b476" }, { "ImportPath": "github.com/Azure/azure-sdk-for-go/management/hostedservice", - "Comment": "v1.2-315-g1cb9dff", - "Rev": "1cb9dff8c37b2918ad1ebd7b294d01100a153d27" + "Comment": "v2.1.1-beta-8-gca4d906", + "Rev": "ca4d906d1c0973ae3022588df7dfa13d53b5b476" }, { "ImportPath": "github.com/Azure/azure-sdk-for-go/management/location", - "Comment": "v1.2-315-g1cb9dff", - "Rev": "1cb9dff8c37b2918ad1ebd7b294d01100a153d27" + "Comment": "v2.1.1-beta-8-gca4d906", + "Rev": "ca4d906d1c0973ae3022588df7dfa13d53b5b476" }, { "ImportPath": "github.com/Azure/azure-sdk-for-go/management/networksecuritygroup", - "Comment": "v1.2-315-g1cb9dff", - "Rev": "1cb9dff8c37b2918ad1ebd7b294d01100a153d27" + "Comment": "v2.1.1-beta-8-gca4d906", + "Rev": "ca4d906d1c0973ae3022588df7dfa13d53b5b476" }, { "ImportPath": "github.com/Azure/azure-sdk-for-go/management/osimage", - "Comment": "v1.2-315-g1cb9dff", - "Rev": "1cb9dff8c37b2918ad1ebd7b294d01100a153d27" + "Comment": "v2.1.1-beta-8-gca4d906", + "Rev": "ca4d906d1c0973ae3022588df7dfa13d53b5b476" }, { "ImportPath": "github.com/Azure/azure-sdk-for-go/management/sql", - "Comment": "v1.2-315-g1cb9dff", - "Rev": "1cb9dff8c37b2918ad1ebd7b294d01100a153d27" + "Comment": "v2.1.1-beta-8-gca4d906", + "Rev": "ca4d906d1c0973ae3022588df7dfa13d53b5b476" }, { "ImportPath": "github.com/Azure/azure-sdk-for-go/management/storageservice", - "Comment": "v1.2-315-g1cb9dff", - "Rev": "1cb9dff8c37b2918ad1ebd7b294d01100a153d27" + "Comment": "v2.1.1-beta-8-gca4d906", + "Rev": "ca4d906d1c0973ae3022588df7dfa13d53b5b476" }, { "ImportPath": "github.com/Azure/azure-sdk-for-go/management/virtualmachine", - "Comment": "v1.2-315-g1cb9dff", - "Rev": "1cb9dff8c37b2918ad1ebd7b294d01100a153d27" + "Comment": "v2.1.1-beta-8-gca4d906", + "Rev": "ca4d906d1c0973ae3022588df7dfa13d53b5b476" }, { "ImportPath": "github.com/Azure/azure-sdk-for-go/management/virtualmachinedisk", - "Comment": "v1.2-315-g1cb9dff", - "Rev": "1cb9dff8c37b2918ad1ebd7b294d01100a153d27" + "Comment": "v2.1.1-beta-8-gca4d906", + "Rev": "ca4d906d1c0973ae3022588df7dfa13d53b5b476" }, { "ImportPath": "github.com/Azure/azure-sdk-for-go/management/virtualmachineimage", - "Comment": "v1.2-315-g1cb9dff", - "Rev": "1cb9dff8c37b2918ad1ebd7b294d01100a153d27" + "Comment": "v2.1.1-beta-8-gca4d906", + "Rev": "ca4d906d1c0973ae3022588df7dfa13d53b5b476" }, { "ImportPath": "github.com/Azure/azure-sdk-for-go/management/virtualnetwork", - "Comment": "v1.2-315-g1cb9dff", - "Rev": "1cb9dff8c37b2918ad1ebd7b294d01100a153d27" + "Comment": "v2.1.1-beta-8-gca4d906", + "Rev": "ca4d906d1c0973ae3022588df7dfa13d53b5b476" }, { "ImportPath": "github.com/Azure/azure-sdk-for-go/management/vmutils", - "Comment": "v1.2-315-g1cb9dff", - "Rev": "1cb9dff8c37b2918ad1ebd7b294d01100a153d27" + "Comment": "v2.1.1-beta-8-gca4d906", + "Rev": "ca4d906d1c0973ae3022588df7dfa13d53b5b476" }, { "ImportPath": "github.com/Azure/azure-sdk-for-go/storage", - "Comment": "v1.2-315-g1cb9dff", - "Rev": "1cb9dff8c37b2918ad1ebd7b294d01100a153d27" + "Comment": "v2.1.1-beta-8-gca4d906", + "Rev": "ca4d906d1c0973ae3022588df7dfa13d53b5b476" }, { "ImportPath": "github.com/CenturyLinkCloud/clc-sdk", @@ -1549,6 +1549,31 @@ "ImportPath": "gopkg.in/ini.v1", "Comment": "v1.8.5", "Rev": "77178f22699a4ecafce485fb8d86b7afeb7e3e28" + }, + { + "ImportPath": "github.com/Azure/go-autorest/autorest", + "Comment": "v7.0.5", + "Rev": "4bdf29b663ebad9598d2c391b73a4b46bdedbf42" + }, + { + "ImportPath": "github.com/Azure/go-autorest/autorest/azure", + "Comment": "v7.0.5", + "Rev": "4bdf29b663ebad9598d2c391b73a4b46bdedbf42" + }, + { + "ImportPath": "github.com/Azure/go-autorest/autorest/date", + "Comment": "v7.0.5", + "Rev": "4bdf29b663ebad9598d2c391b73a4b46bdedbf42" + }, + { + "ImportPath": "github.com/dgrijalva/jwt-go", + "Comment": "v2.4.0-11-gf219341", + "Rev": "f2193411bd642f7db03249fd79d5292c9b34916a" + }, + { + "ImportPath": "github.com/Azure/go-autorest/autorest/to", + "Comment": "v7.0.5", + "Rev": "4bdf29b663ebad9598d2c391b73a4b46bdedbf42" } ] } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/azure/azure.go b/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/azure/azure.go deleted file mode 100644 index e4358930288d..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/azure/azure.go +++ /dev/null @@ -1,72 +0,0 @@ -/* -Package azure provides Azure-specific implementations used with AutoRest. - -See the included examples for more detail. -*/ -package azure - -import ( - "net/http" - "strconv" - - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" -) - -const ( - // HeaderClientID is the Azure extension header to set a user-specified request ID. - HeaderClientID = "x-ms-client-request-id" - - // HeaderReturnClientID is the Azure extension header to set if the user-specified request ID - // should be included in the response. - HeaderReturnClientID = "x-ms-return-client-request-id" - - // HeaderRequestID is the Azure extension header of the service generated request ID returned - // in the response. - HeaderRequestID = "x-ms-request-id" -) - -// WithReturningClientID returns a PrepareDecorator that adds an HTTP extension header of -// x-ms-client-request-id whose value is the passed, undecorated UUID (e.g., -// "0F39878C-5F76-4DB8-A25D-61D2C193C3CA"). It also sets the x-ms-return-client-request-id -// header to true such that UUID accompanies the http.Response. -func WithReturningClientID(uuid string) autorest.PrepareDecorator { - preparer := autorest.CreatePreparer( - WithClientID(uuid), - WithReturnClientID(true)) - - return func(p autorest.Preparer) autorest.Preparer { - return autorest.PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err != nil { - return r, err - } - return preparer.Prepare(r) - }) - } -} - -// WithClientID returns a PrepareDecorator that adds an HTTP extension header of -// x-ms-client-request-id whose value is passed, undecorated UUID (e.g., -// "0F39878C-5F76-4DB8-A25D-61D2C193C3CA"). -func WithClientID(uuid string) autorest.PrepareDecorator { - return autorest.WithHeader(HeaderClientID, uuid) -} - -// WithReturnClientID returns a PrepareDecorator that adds an HTTP extension header of -// x-ms-return-client-request-id whose boolean value indicates if the value of the -// x-ms-client-request-id header should be included in the http.Response. -func WithReturnClientID(b bool) autorest.PrepareDecorator { - return autorest.WithHeader(HeaderReturnClientID, strconv.FormatBool(b)) -} - -// ExtractClientID extracts the client identifier from the x-ms-client-request-id header set on the -// http.Request sent to the service (and returned in the http.Response) -func ExtractClientID(resp *http.Response) string { - return autorest.ExtractHeaderValue(HeaderClientID, resp) -} - -// ExtractRequestID extracts the Azure server generated request identifier from the -// x-ms-request-id header. -func ExtractRequestID(resp *http.Response) string { - return autorest.ExtractHeaderValue(HeaderRequestID, resp) -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/client.go b/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/client.go deleted file mode 100644 index 09202333a315..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/client.go +++ /dev/null @@ -1,288 +0,0 @@ -package autorest - -import ( - "bytes" - "io" - "io/ioutil" - "log" - "net/http" - "time" -) - -const ( - // DefaultPollingDelay is the default delay between polling requests (only used if the - // http.Request lacks a well-formed Retry-After header). - DefaultPollingDelay = 60 * time.Second - - // DefaultPollingDuration is the default total polling duration. - DefaultPollingDuration = 15 * time.Minute -) - -// PollingMode sets how, if at all, clients composed with Client will poll. -type PollingMode string - -const ( - // PollUntilAttempts polling mode polls until reaching a maximum number of attempts. - PollUntilAttempts PollingMode = "poll-until-attempts" - - // PollUntilDuration polling mode polls until a specified time.Duration has passed. - PollUntilDuration PollingMode = "poll-until-duration" - - // DoNotPoll disables polling. - DoNotPoll PollingMode = "not-at-all" -) - -const ( - requestFormat = `HTTP Request Begin =================================================== -%s -===================================================== HTTP Request End -` - responseFormat = `HTTP Response Begin =================================================== -%s -===================================================== HTTP Response End -` -) - -// LoggingInspector implements request and response inspectors that log the full request and -// response to a supplied log. -type LoggingInspector struct { - Logger *log.Logger -} - -// WithInspection returns a PrepareDecorator that emits the http.Request to the supplied logger. The -// body is restored after being emitted. -// -// Note: Since it reads the entire Body, this decorator should not be used where body streaming is -// important. It is best used to trace JSON or similar body values. -func (li LoggingInspector) WithInspection() PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - var body, b bytes.Buffer - - defer r.Body.Close() - - r.Body = ioutil.NopCloser(io.TeeReader(r.Body, &body)) - r.Write(&b) - - li.Logger.Printf(requestFormat, b.String()) - - r.Body = ioutil.NopCloser(&body) - return p.Prepare(r) - }) - } -} - -// ByInspecting returns a RespondDecorator that emits the http.Response to the supplied logger. The -// body is restored after being emitted. -// -// Note: Since it reads the entire Body, this decorator should not be used where body streaming is -// important. It is best used to trace JSON or similar body values. -func (li LoggingInspector) ByInspecting() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - var body, b bytes.Buffer - - defer resp.Body.Close() - - resp.Body = ioutil.NopCloser(io.TeeReader(resp.Body, &body)) - resp.Write(&b) - - li.Logger.Printf(responseFormat, b.String()) - - resp.Body = ioutil.NopCloser(&body) - return r.Respond(resp) - }) - } -} - -var ( - // DefaultClient is the base from which generated clients should create a Client instance. Users - // can then established widely used Client defaults by replacing or modifying the DefaultClient - // before instantiating a generated client. - DefaultClient = Client{PollingMode: PollUntilDuration, PollingDuration: DefaultPollingDuration} -) - -// Client is the base for autorest generated clients. It provides default, "do nothing" -// implementations of an Authorizer, RequestInspector, and ResponseInspector. It also returns the -// standard, undecorated http.Client as a default Sender. Lastly, it supports basic request polling, -// limited to a maximum number of attempts or a specified duration. -// -// Generated clients should also use Error (see NewError and NewErrorWithError) for errors and -// return responses that compose with Response. -// -// Most customization of generated clients is best achieved by supplying a custom Authorizer, custom -// RequestInspector, and / or custom ResponseInspector. Users may log requests, implement circuit -// breakers (see https://msdn.microsoft.com/en-us/library/dn589784.aspx) or otherwise influence -// sending the request by providing a decorated Sender. -type Client struct { - Authorizer Authorizer - Sender Sender - RequestInspector PrepareDecorator - ResponseInspector RespondDecorator - - PollingMode PollingMode - PollingAttempts int - PollingDuration time.Duration - - // UserAgent, if not empty, will be set as the HTTP User-Agent header on all requests sent - // through the Do method. - UserAgent string -} - -// NewClientWithUserAgent returns an instance of the DefaultClient with the UserAgent set to the -// passed string. -func NewClientWithUserAgent(ua string) Client { - c := DefaultClient - c.UserAgent = ua - return c -} - -// IsPollingAllowed returns an error if the client allows polling and the passed http.Response -// requires it, otherwise it returns nil. -func (c Client) IsPollingAllowed(resp *http.Response, codes ...int) error { - if c.DoNotPoll() && ResponseRequiresPolling(resp, codes...) { - return NewErrorWithStatusCode("autorest/Client", "IsPollingAllowed", resp.StatusCode, "Response to %s requires polling but polling is disabled", - resp.Request.URL) - } - return nil -} - -// PollAsNeeded is a convenience method that will poll if the passed http.Response requires it. -func (c Client) PollAsNeeded(resp *http.Response, codes ...int) (*http.Response, error) { - if !ResponseRequiresPolling(resp, codes...) { - return resp, nil - } - - if c.DoNotPoll() { - return resp, NewErrorWithStatusCode("autorest/Client", "PollAsNeeded", resp.StatusCode, "Polling for %s is required, but polling is disabled", - resp.Request.URL) - } - - req, err := NewPollingRequest(resp, c) - if err != nil { - return resp, NewErrorWithError(err, "autorest/Client", "PollAsNeeded", resp.StatusCode, "Unable to create polling request for response to %s", - resp.Request.URL) - } - - Prepare(req, - c.WithInspection()) - - if c.PollForAttempts() { - return PollForAttempts(c, req, DefaultPollingDelay, c.PollingAttempts, codes...) - } - return PollForDuration(c, req, DefaultPollingDelay, c.PollingDuration, codes...) -} - -// DoNotPoll returns true if the client should not poll, false otherwise. -func (c Client) DoNotPoll() bool { - return len(c.PollingMode) == 0 || c.PollingMode == DoNotPoll -} - -// PollForAttempts returns true if the PollingMode is set to ForAttempts, false otherwise. -func (c Client) PollForAttempts() bool { - return c.PollingMode == PollUntilAttempts -} - -// PollForDuration return true if the PollingMode is set to ForDuration, false otherwise. -func (c Client) PollForDuration() bool { - return c.PollingMode == PollUntilDuration -} - -// Send sends the passed http.Request after applying authorization. It will poll if the client -// allows polling and the http.Response status code requires it. It will close the http.Response -// Body if the request returns an error. -func (c Client) Send(req *http.Request, codes ...int) (*http.Response, error) { - if len(codes) == 0 { - codes = []int{http.StatusOK} - } - - req, err := Prepare(req, - c.WithAuthorization(), - c.WithInspection()) - if err != nil { - return nil, NewErrorWithError(err, "autorest/Client", "Send", UndefinedStatusCode, "Preparing request failed") - } - - resp, err := SendWithSender(c, req, - DoErrorUnlessStatusCode(codes...)) - if err == nil { - err = c.IsPollingAllowed(resp) - if err == nil { - resp, err = c.PollAsNeeded(resp) - } - } - - if err != nil { - Respond(resp, - ByClosing()) - } - - return resp, err -} - -// Do implements the Sender interface by invoking the active Sender. If Sender is not set, it uses -// a new instance of http.Client. In both cases it will, if UserAgent is set, apply set the -// User-Agent header. -func (c Client) Do(r *http.Request) (*http.Response, error) { - if len(c.UserAgent) > 0 { - r, _ = Prepare(r, WithUserAgent(c.UserAgent)) - } - return c.sender().Do(r) -} - -// sender returns the Sender to which to send requests. -func (c Client) sender() Sender { - if c.Sender == nil { - return http.DefaultClient - } - return c.Sender -} - -// WithAuthorization is a convenience method that returns the WithAuthorization PrepareDecorator -// from the current Authorizer. If not Authorizer is set, it uses the NullAuthorizer. -func (c Client) WithAuthorization() PrepareDecorator { - return c.authorizer().WithAuthorization() -} - -// authorizer returns the Authorizer to use. -func (c Client) authorizer() Authorizer { - if c.Authorizer == nil { - return NullAuthorizer{} - } - return c.Authorizer -} - -// WithInspection is a convenience method that passes the request to the supplied RequestInspector, -// if present, or returns the WithNothing PrepareDecorator otherwise. -func (c Client) WithInspection() PrepareDecorator { - if c.RequestInspector == nil { - return WithNothing() - } - return c.RequestInspector -} - -// ByInspecting is a convenience method that passes the response to the supplied ResponseInspector, -// if present, or returns the ByIgnoring RespondDecorator otherwise. -func (c Client) ByInspecting() RespondDecorator { - if c.ResponseInspector == nil { - return ByIgnoring() - } - return c.ResponseInspector -} - -// Response serves as the base for all responses from generated clients. It provides access to the -// last http.Response. -type Response struct { - *http.Response `json:"-"` -} - -// GetPollingDelay extracts the polling delay from the Retry-After header of the response. If -// the header is absent or is malformed, it will return the supplied default delay time.Duration. -func (r Response) GetPollingDelay(defaultDelay time.Duration) time.Duration { - return GetPollingDelay(r.Response, defaultDelay) -} - -// GetPollingLocation retrieves the polling URL from the Location header of the response. -func (r Response) GetPollingLocation() string { - return GetPollingLocation(r.Response) -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/error.go b/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/error.go deleted file mode 100644 index 1ad8bd07a0a8..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/error.go +++ /dev/null @@ -1,114 +0,0 @@ -package autorest - -import ( - "fmt" -) - -const ( - // UndefinedStatusCode is used when HTTP status code is not available for an error. - UndefinedStatusCode = 0 -) - -// Error describes the methods implemented by autorest errors. -type Error interface { - error - - // PackageType should return the package type of the object emitting the error. For types, the - // value should match that produced the the '%T' format specifier of the fmt package. For other - // elements, such as functions, it returns just the package name (e.g., "autorest"). - PackageType() string - - // Method should return the name of the method raising the error. - Method() string - - // StatusCode returns the HTTP Response StatusCode (if non-zero) that led to the error. - StatusCode() int - - // Message should return the error message. - Message() string - - // String should return a formatted containing all available details (i.e., PackageType, Method, - // Message, and original error (if any)). - String() string - - // Original should return the original error, if any, and nil otherwise. - Original() error -} - -type baseError struct { - packageType string - method string - statusCode int - message string - - original error -} - -// NewError creates a new Error conforming object from the passed packageType, method, and -// message. message is treated as a format string to which the optional args apply. -func NewError(packageType string, method string, message string, args ...interface{}) Error { - return NewErrorWithError(nil, packageType, method, UndefinedStatusCode, message, args...) -} - -// NewErrorWithStatusCode creates a new Error conforming object from the passed packageType, method, -// statusCode, and message. message is treated as a format string to which the optional args apply. -func NewErrorWithStatusCode(packageType string, method string, statusCode int, message string, args ...interface{}) Error { - return NewErrorWithError(nil, packageType, method, statusCode, message, args...) -} - -// NewErrorWithError creates a new Error conforming object from the passed packageType, method, -// statusCode, message, and original error. message is treated as a format string to which the -// optional args apply. -func NewErrorWithError(original error, packageType string, method string, statusCode int, message string, args ...interface{}) Error { - if _, ok := original.(Error); ok { - return original.(Error) - } - return baseError{ - packageType: packageType, - method: method, - statusCode: statusCode, - message: fmt.Sprintf(message, args...), - original: original, - } -} - -// PackageType returns the package type of the object emitting the error. For types, the value -// matches that produced the the '%T' format specifier of the fmt package. For other elements, -// such as functions, it returns just the package name (e.g., "autorest"). -func (be baseError) PackageType() string { - return be.packageType -} - -// Method returns the name of the method raising the error. -func (be baseError) Method() string { - return be.method -} - -// StatusCode returns the HTTP Response StatusCode (if non-zero) that led to the error. -func (be baseError) StatusCode() int { - return be.statusCode -} - -// Message is the error message. -func (be baseError) Message() string { - return be.message -} - -// Original returns the original error, if any, and nil otherwise. -func (be baseError) Original() error { - return be.original -} - -// Error returns the same formatted string as String. -func (be baseError) Error() string { - return be.String() -} - -// String returns a formatted containing all available details (i.e., PackageType, Method, -// StatusCode, Message, and original error (if any)). -func (be baseError) String() string { - if be.original == nil { - return fmt.Sprintf("%s:%s %v %s", be.packageType, be.method, be.statusCode, be.message) - } - return fmt.Sprintf("%s:%s %v %s -- Original Error: %v", be.packageType, be.method, be.statusCode, be.message, be.original) -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/bmp-string.go b/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/bmp-string.go deleted file mode 100644 index 284d2a68f1ee..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/bmp-string.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package pkcs12 - -import ( - "errors" - "unicode/utf16" -) - -// bmpString returns s encoded in UCS-2 with a zero terminator. -func bmpString(s string) ([]byte, error) { - // References: - // https://tools.ietf.org/html/rfc7292#appendix-B.1 - // http://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane - // - non-BMP characters are encoded in UTF 16 by using a surrogate pair of 16-bit codes - // EncodeRune returns 0xfffd if the rune does not need special encoding - // - the above RFC provides the info that BMPStrings are NULL terminated. - - ret := make([]byte, 0, 2*len(s)+2) - - for _, r := range s { - if t, _ := utf16.EncodeRune(r); t != 0xfffd { - return nil, errors.New("pkcs12: string contains characters that cannot be encoded in UCS-2") - } - ret = append(ret, byte(r/256), byte(r%256)) - } - - return append(ret, 0, 0), nil -} - -func decodeBMPString(bmpString []byte) (string, error) { - if len(bmpString)%2 != 0 { - return "", errors.New("pkcs12: odd-length BMP string") - } - - // strip terminator if present - if l := len(bmpString); l >= 2 && bmpString[l-1] == 0 && bmpString[l-2] == 0 { - bmpString = bmpString[:l-2] - } - - s := make([]uint16, 0, len(bmpString)/2) - for len(bmpString) > 0 { - s = append(s, uint16(bmpString[0])<<8+uint16(bmpString[1])) - bmpString = bmpString[2:] - } - - return string(utf16.Decode(s)), nil -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/crypto.go b/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/crypto.go deleted file mode 100644 index 2bb8e24709fa..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/crypto.go +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package pkcs12 - -import ( - "bytes" - "crypto/cipher" - "crypto/des" - "crypto/x509/pkix" - "encoding/asn1" - "errors" - - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/internal/rc2" -) - -var ( - oidPBEWithSHAAnd3KeyTripleDESCBC = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 1, 3}) - oidPBEWithSHAAnd40BitRC2CBC = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 1, 6}) -) - -// pbeCipher is an abstraction of a PKCS#12 cipher. -type pbeCipher interface { - // create returns a cipher.Block given a key. - create(key []byte) (cipher.Block, error) - // deriveKey returns a key derived from the given password and salt. - deriveKey(salt, password []byte, iterations int) []byte - // deriveKey returns an IV derived from the given password and salt. - deriveIV(salt, password []byte, iterations int) []byte -} - -type shaWithTripleDESCBC struct{} - -func (shaWithTripleDESCBC) create(key []byte) (cipher.Block, error) { - return des.NewTripleDESCipher(key) -} - -func (shaWithTripleDESCBC) deriveKey(salt, password []byte, iterations int) []byte { - return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 1, 24) -} - -func (shaWithTripleDESCBC) deriveIV(salt, password []byte, iterations int) []byte { - return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 2, 8) -} - -type shaWith40BitRC2CBC struct{} - -func (shaWith40BitRC2CBC) create(key []byte) (cipher.Block, error) { - return rc2.New(key, len(key)*8) -} - -func (shaWith40BitRC2CBC) deriveKey(salt, password []byte, iterations int) []byte { - return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 1, 5) -} - -func (shaWith40BitRC2CBC) deriveIV(salt, password []byte, iterations int) []byte { - return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 2, 8) -} - -type pbeParams struct { - Salt []byte - Iterations int -} - -func pbDecrypterFor(algorithm pkix.AlgorithmIdentifier, password []byte) (cipher.BlockMode, int, error) { - var cipherType pbeCipher - - switch { - case algorithm.Algorithm.Equal(oidPBEWithSHAAnd3KeyTripleDESCBC): - cipherType = shaWithTripleDESCBC{} - case algorithm.Algorithm.Equal(oidPBEWithSHAAnd40BitRC2CBC): - cipherType = shaWith40BitRC2CBC{} - default: - return nil, 0, NotImplementedError("algorithm " + algorithm.Algorithm.String() + " is not supported") - } - - var params pbeParams - if err := unmarshal(algorithm.Parameters.FullBytes, ¶ms); err != nil { - return nil, 0, err - } - - key := cipherType.deriveKey(params.Salt, password, params.Iterations) - iv := cipherType.deriveIV(params.Salt, password, params.Iterations) - - block, err := cipherType.create(key) - if err != nil { - return nil, 0, err - } - - return cipher.NewCBCDecrypter(block, iv), block.BlockSize(), nil -} - -func pbDecrypt(info decryptable, password []byte) (decrypted []byte, err error) { - cbc, blockSize, err := pbDecrypterFor(info.Algorithm(), password) - if err != nil { - return nil, err - } - - encrypted := info.Data() - if len(encrypted) == 0 { - return nil, errors.New("pkcs12: empty encrypted data") - } - if len(encrypted)%blockSize != 0 { - return nil, errors.New("pkcs12: input is not a multiple of the block size") - } - decrypted = make([]byte, len(encrypted)) - cbc.CryptBlocks(decrypted, encrypted) - - psLen := int(decrypted[len(decrypted)-1]) - if psLen == 0 || psLen > blockSize { - return nil, ErrDecryption - } - - if len(decrypted) < psLen { - return nil, ErrDecryption - } - ps := decrypted[len(decrypted)-psLen:] - decrypted = decrypted[:len(decrypted)-psLen] - if bytes.Compare(ps, bytes.Repeat([]byte{byte(psLen)}, psLen)) != 0 { - return nil, ErrDecryption - } - - return -} - -// decryptable abstracts a object that contains ciphertext. -type decryptable interface { - Algorithm() pkix.AlgorithmIdentifier - Data() []byte -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/errors.go b/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/errors.go deleted file mode 100644 index 7377ce6fb2b8..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/errors.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package pkcs12 - -import "errors" - -var ( - // ErrDecryption represents a failure to decrypt the input. - ErrDecryption = errors.New("pkcs12: decryption error, incorrect padding") - - // ErrIncorrectPassword is returned when an incorrect password is detected. - // Usually, P12/PFX data is signed to be able to verify the password. - ErrIncorrectPassword = errors.New("pkcs12: decryption password incorrect") -) - -// NotImplementedError indicates that the input is not currently supported. -type NotImplementedError string - -func (e NotImplementedError) Error() string { - return "pkcs12: " + string(e) -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/internal/rc2/rc2.go b/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/internal/rc2/rc2.go deleted file mode 100644 index 8c7090258c5a..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/internal/rc2/rc2.go +++ /dev/null @@ -1,274 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package rc2 implements the RC2 cipher -/* -https://www.ietf.org/rfc/rfc2268.txt -http://people.csail.mit.edu/rivest/pubs/KRRR98.pdf - -This code is licensed under the MIT license. -*/ -package rc2 - -import ( - "crypto/cipher" - "encoding/binary" -) - -// The rc2 block size in bytes -const BlockSize = 8 - -type rc2Cipher struct { - k [64]uint16 -} - -// New returns a new rc2 cipher with the given key and effective key length t1 -func New(key []byte, t1 int) (cipher.Block, error) { - // TODO(dgryski): error checking for key length - return &rc2Cipher{ - k: expandKey(key, t1), - }, nil -} - -func (*rc2Cipher) BlockSize() int { return BlockSize } - -var piTable = [256]byte{ - 0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d, - 0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e, 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2, - 0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13, 0x61, 0x45, 0x6d, 0x8d, 0x09, 0x81, 0x7d, 0x32, - 0xbd, 0x8f, 0x40, 0xeb, 0x86, 0xb7, 0x7b, 0x0b, 0xf0, 0x95, 0x21, 0x22, 0x5c, 0x6b, 0x4e, 0x82, - 0x54, 0xd6, 0x65, 0x93, 0xce, 0x60, 0xb2, 0x1c, 0x73, 0x56, 0xc0, 0x14, 0xa7, 0x8c, 0xf1, 0xdc, - 0x12, 0x75, 0xca, 0x1f, 0x3b, 0xbe, 0xe4, 0xd1, 0x42, 0x3d, 0xd4, 0x30, 0xa3, 0x3c, 0xb6, 0x26, - 0x6f, 0xbf, 0x0e, 0xda, 0x46, 0x69, 0x07, 0x57, 0x27, 0xf2, 0x1d, 0x9b, 0xbc, 0x94, 0x43, 0x03, - 0xf8, 0x11, 0xc7, 0xf6, 0x90, 0xef, 0x3e, 0xe7, 0x06, 0xc3, 0xd5, 0x2f, 0xc8, 0x66, 0x1e, 0xd7, - 0x08, 0xe8, 0xea, 0xde, 0x80, 0x52, 0xee, 0xf7, 0x84, 0xaa, 0x72, 0xac, 0x35, 0x4d, 0x6a, 0x2a, - 0x96, 0x1a, 0xd2, 0x71, 0x5a, 0x15, 0x49, 0x74, 0x4b, 0x9f, 0xd0, 0x5e, 0x04, 0x18, 0xa4, 0xec, - 0xc2, 0xe0, 0x41, 0x6e, 0x0f, 0x51, 0xcb, 0xcc, 0x24, 0x91, 0xaf, 0x50, 0xa1, 0xf4, 0x70, 0x39, - 0x99, 0x7c, 0x3a, 0x85, 0x23, 0xb8, 0xb4, 0x7a, 0xfc, 0x02, 0x36, 0x5b, 0x25, 0x55, 0x97, 0x31, - 0x2d, 0x5d, 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae, 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9, - 0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c, 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9, - 0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e, - 0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad, -} - -func expandKey(key []byte, t1 int) [64]uint16 { - - l := make([]byte, 128) - copy(l, key) - - var t = len(key) - var t8 = (t1 + 7) / 8 - var tm = byte(255 % uint(1<<(8+uint(t1)-8*uint(t8)))) - - for i := len(key); i < 128; i++ { - l[i] = piTable[l[i-1]+l[uint8(i-t)]] - } - - l[128-t8] = piTable[l[128-t8]&tm] - - for i := 127 - t8; i >= 0; i-- { - l[i] = piTable[l[i+1]^l[i+t8]] - } - - var k [64]uint16 - - for i := range k { - k[i] = uint16(l[2*i]) + uint16(l[2*i+1])*256 - } - - return k -} - -func rotl16(x uint16, b uint) uint16 { - return (x >> (16 - b)) | (x << b) -} - -func (c *rc2Cipher) Encrypt(dst, src []byte) { - - r0 := binary.LittleEndian.Uint16(src[0:]) - r1 := binary.LittleEndian.Uint16(src[2:]) - r2 := binary.LittleEndian.Uint16(src[4:]) - r3 := binary.LittleEndian.Uint16(src[6:]) - - var j int - - for j <= 16 { - // mix r0 - r0 = r0 + c.k[j] + (r3 & r2) + ((^r3) & r1) - r0 = rotl16(r0, 1) - j++ - - // mix r1 - r1 = r1 + c.k[j] + (r0 & r3) + ((^r0) & r2) - r1 = rotl16(r1, 2) - j++ - - // mix r2 - r2 = r2 + c.k[j] + (r1 & r0) + ((^r1) & r3) - r2 = rotl16(r2, 3) - j++ - - // mix r3 - r3 = r3 + c.k[j] + (r2 & r1) + ((^r2) & r0) - r3 = rotl16(r3, 5) - j++ - - } - - r0 = r0 + c.k[r3&63] - r1 = r1 + c.k[r0&63] - r2 = r2 + c.k[r1&63] - r3 = r3 + c.k[r2&63] - - for j <= 40 { - - // mix r0 - r0 = r0 + c.k[j] + (r3 & r2) + ((^r3) & r1) - r0 = rotl16(r0, 1) - j++ - - // mix r1 - r1 = r1 + c.k[j] + (r0 & r3) + ((^r0) & r2) - r1 = rotl16(r1, 2) - j++ - - // mix r2 - r2 = r2 + c.k[j] + (r1 & r0) + ((^r1) & r3) - r2 = rotl16(r2, 3) - j++ - - // mix r3 - r3 = r3 + c.k[j] + (r2 & r1) + ((^r2) & r0) - r3 = rotl16(r3, 5) - j++ - - } - - r0 = r0 + c.k[r3&63] - r1 = r1 + c.k[r0&63] - r2 = r2 + c.k[r1&63] - r3 = r3 + c.k[r2&63] - - for j <= 60 { - - // mix r0 - r0 = r0 + c.k[j] + (r3 & r2) + ((^r3) & r1) - r0 = rotl16(r0, 1) - j++ - - // mix r1 - r1 = r1 + c.k[j] + (r0 & r3) + ((^r0) & r2) - r1 = rotl16(r1, 2) - j++ - - // mix r2 - r2 = r2 + c.k[j] + (r1 & r0) + ((^r1) & r3) - r2 = rotl16(r2, 3) - j++ - - // mix r3 - r3 = r3 + c.k[j] + (r2 & r1) + ((^r2) & r0) - r3 = rotl16(r3, 5) - j++ - } - - binary.LittleEndian.PutUint16(dst[0:], r0) - binary.LittleEndian.PutUint16(dst[2:], r1) - binary.LittleEndian.PutUint16(dst[4:], r2) - binary.LittleEndian.PutUint16(dst[6:], r3) -} - -func (c *rc2Cipher) Decrypt(dst, src []byte) { - - r0 := binary.LittleEndian.Uint16(src[0:]) - r1 := binary.LittleEndian.Uint16(src[2:]) - r2 := binary.LittleEndian.Uint16(src[4:]) - r3 := binary.LittleEndian.Uint16(src[6:]) - - j := 63 - - for j >= 44 { - // unmix r3 - r3 = rotl16(r3, 16-5) - r3 = r3 - c.k[j] - (r2 & r1) - ((^r2) & r0) - j-- - - // unmix r2 - r2 = rotl16(r2, 16-3) - r2 = r2 - c.k[j] - (r1 & r0) - ((^r1) & r3) - j-- - - // unmix r1 - r1 = rotl16(r1, 16-2) - r1 = r1 - c.k[j] - (r0 & r3) - ((^r0) & r2) - j-- - - // unmix r0 - r0 = rotl16(r0, 16-1) - r0 = r0 - c.k[j] - (r3 & r2) - ((^r3) & r1) - j-- - } - - r3 = r3 - c.k[r2&63] - r2 = r2 - c.k[r1&63] - r1 = r1 - c.k[r0&63] - r0 = r0 - c.k[r3&63] - - for j >= 20 { - // unmix r3 - r3 = rotl16(r3, 16-5) - r3 = r3 - c.k[j] - (r2 & r1) - ((^r2) & r0) - j-- - - // unmix r2 - r2 = rotl16(r2, 16-3) - r2 = r2 - c.k[j] - (r1 & r0) - ((^r1) & r3) - j-- - - // unmix r1 - r1 = rotl16(r1, 16-2) - r1 = r1 - c.k[j] - (r0 & r3) - ((^r0) & r2) - j-- - - // unmix r0 - r0 = rotl16(r0, 16-1) - r0 = r0 - c.k[j] - (r3 & r2) - ((^r3) & r1) - j-- - - } - - r3 = r3 - c.k[r2&63] - r2 = r2 - c.k[r1&63] - r1 = r1 - c.k[r0&63] - r0 = r0 - c.k[r3&63] - - for j >= 0 { - - // unmix r3 - r3 = rotl16(r3, 16-5) - r3 = r3 - c.k[j] - (r2 & r1) - ((^r2) & r0) - j-- - - // unmix r2 - r2 = rotl16(r2, 16-3) - r2 = r2 - c.k[j] - (r1 & r0) - ((^r1) & r3) - j-- - - // unmix r1 - r1 = rotl16(r1, 16-2) - r1 = r1 - c.k[j] - (r0 & r3) - ((^r0) & r2) - j-- - - // unmix r0 - r0 = rotl16(r0, 16-1) - r0 = r0 - c.k[j] - (r3 & r2) - ((^r3) & r1) - j-- - - } - - binary.LittleEndian.PutUint16(dst[0:], r0) - binary.LittleEndian.PutUint16(dst[2:], r1) - binary.LittleEndian.PutUint16(dst[4:], r2) - binary.LittleEndian.PutUint16(dst[6:], r3) -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/mac.go b/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/mac.go deleted file mode 100644 index 5f38aa7de83c..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/mac.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package pkcs12 - -import ( - "crypto/hmac" - "crypto/sha1" - "crypto/x509/pkix" - "encoding/asn1" -) - -type macData struct { - Mac digestInfo - MacSalt []byte - Iterations int `asn1:"optional,default:1"` -} - -// from PKCS#7: -type digestInfo struct { - Algorithm pkix.AlgorithmIdentifier - Digest []byte -} - -var ( - oidSHA1 = asn1.ObjectIdentifier([]int{1, 3, 14, 3, 2, 26}) -) - -func verifyMac(macData *macData, message, password []byte) error { - if !macData.Mac.Algorithm.Algorithm.Equal(oidSHA1) { - return NotImplementedError("unknown digest algorithm: " + macData.Mac.Algorithm.Algorithm.String()) - } - - key := pbkdf(sha1Sum, 20, 64, macData.MacSalt, password, macData.Iterations, 3, 20) - - mac := hmac.New(sha1.New, key) - mac.Write(message) - expectedMAC := mac.Sum(nil) - - if !hmac.Equal(macData.Mac.Digest, expectedMAC) { - return ErrIncorrectPassword - } - return nil -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/pbkdf.go b/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/pbkdf.go deleted file mode 100644 index 5c419d41e32c..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/pbkdf.go +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package pkcs12 - -import ( - "bytes" - "crypto/sha1" - "math/big" -) - -var ( - one = big.NewInt(1) -) - -// sha1Sum returns the SHA-1 hash of in. -func sha1Sum(in []byte) []byte { - sum := sha1.Sum(in) - return sum[:] -} - -// fillWithRepeats returns v*ceiling(len(pattern) / v) bytes consisting of -// repeats of pattern. -func fillWithRepeats(pattern []byte, v int) []byte { - if len(pattern) == 0 { - return nil - } - outputLen := v * ((len(pattern) + v - 1) / v) - return bytes.Repeat(pattern, (outputLen+len(pattern)-1)/len(pattern))[:outputLen] -} - -func pbkdf(hash func([]byte) []byte, u, v int, salt, password []byte, r int, ID byte, size int) (key []byte) { - // implementation of https://tools.ietf.org/html/rfc7292#appendix-B.2 , RFC text verbatim in comments - - // Let H be a hash function built around a compression function f: - - // Z_2^u x Z_2^v -> Z_2^u - - // (that is, H has a chaining variable and output of length u bits, and - // the message input to the compression function of H is v bits). The - // values for u and v are as follows: - - // HASH FUNCTION VALUE u VALUE v - // MD2, MD5 128 512 - // SHA-1 160 512 - // SHA-224 224 512 - // SHA-256 256 512 - // SHA-384 384 1024 - // SHA-512 512 1024 - // SHA-512/224 224 1024 - // SHA-512/256 256 1024 - - // Furthermore, let r be the iteration count. - - // We assume here that u and v are both multiples of 8, as are the - // lengths of the password and salt strings (which we denote by p and s, - // respectively) and the number n of pseudorandom bits required. In - // addition, u and v are of course non-zero. - - // For information on security considerations for MD5 [19], see [25] and - // [1], and on those for MD2, see [18]. - - // The following procedure can be used to produce pseudorandom bits for - // a particular "purpose" that is identified by a byte called "ID". - // This standard specifies 3 different values for the ID byte: - - // 1. If ID=1, then the pseudorandom bits being produced are to be used - // as key material for performing encryption or decryption. - - // 2. If ID=2, then the pseudorandom bits being produced are to be used - // as an IV (Initial Value) for encryption or decryption. - - // 3. If ID=3, then the pseudorandom bits being produced are to be used - // as an integrity key for MACing. - - // 1. Construct a string, D (the "diversifier"), by concatenating v/8 - // copies of ID. - var D []byte - for i := 0; i < v; i++ { - D = append(D, ID) - } - - // 2. Concatenate copies of the salt together to create a string S of - // length v(ceiling(s/v)) bits (the final copy of the salt may be - // truncated to create S). Note that if the salt is the empty - // string, then so is S. - - S := fillWithRepeats(salt, v) - - // 3. Concatenate copies of the password together to create a string P - // of length v(ceiling(p/v)) bits (the final copy of the password - // may be truncated to create P). Note that if the password is the - // empty string, then so is P. - - P := fillWithRepeats(password, v) - - // 4. Set I=S||P to be the concatenation of S and P. - I := append(S, P...) - - // 5. Set c=ceiling(n/u). - c := (size + u - 1) / u - - // 6. For i=1, 2, ..., c, do the following: - A := make([]byte, c*20) - var IjBuf []byte - for i := 0; i < c; i++ { - // A. Set A2=H^r(D||I). (i.e., the r-th hash of D||1, - // H(H(H(... H(D||I)))) - Ai := hash(append(D, I...)) - for j := 1; j < r; j++ { - Ai = hash(Ai) - } - copy(A[i*20:], Ai[:]) - - if i < c-1 { // skip on last iteration - // B. Concatenate copies of Ai to create a string B of length v - // bits (the final copy of Ai may be truncated to create B). - var B []byte - for len(B) < v { - B = append(B, Ai[:]...) - } - B = B[:v] - - // C. Treating I as a concatenation I_0, I_1, ..., I_(k-1) of v-bit - // blocks, where k=ceiling(s/v)+ceiling(p/v), modify I by - // setting I_j=(I_j+B+1) mod 2^v for each j. - { - Bbi := new(big.Int).SetBytes(B) - Ij := new(big.Int) - - for j := 0; j < len(I)/v; j++ { - Ij.SetBytes(I[j*v : (j+1)*v]) - Ij.Add(Ij, Bbi) - Ij.Add(Ij, one) - Ijb := Ij.Bytes() - // We expect Ijb to be exactly v bytes, - // if it is longer or shorter we must - // adjust it accordingly. - if len(Ijb) > v { - Ijb = Ijb[len(Ijb)-v:] - } - if len(Ijb) < v { - if IjBuf == nil { - IjBuf = make([]byte, v) - } - bytesShort := v - len(Ijb) - for i := 0; i < bytesShort; i++ { - IjBuf[i] = 0 - } - copy(IjBuf[bytesShort:], Ijb) - Ijb = IjBuf - } - copy(I[j*v:(j+1)*v], Ijb) - } - } - } - } - // 7. Concatenate A_1, A_2, ..., A_c together to form a pseudorandom - // bit string, A. - - // 8. Use the first n bits of A as the output of this entire process. - return A[:size] - - // If the above process is being used to generate a DES key, the process - // should be used to create 64 random bits, and the key's parity bits - // should be set after the 64 bits have been produced. Similar concerns - // hold for 2-key and 3-key triple-DES keys, for CDMF keys, and for any - // similar keys with parity bits "built into them". -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/pkcs12.go b/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/pkcs12.go deleted file mode 100644 index e8e1799886a2..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/pkcs12.go +++ /dev/null @@ -1,342 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package pkcs12 implements some of PKCS#12. -// -// This implementation is distilled from https://tools.ietf.org/html/rfc7292 -// and referenced documents. It is intended for decoding P12/PFX-stored -// certificates and keys for use with the crypto/tls package. -package pkcs12 - -import ( - "crypto/ecdsa" - "crypto/rsa" - "crypto/x509" - "crypto/x509/pkix" - "encoding/asn1" - "encoding/hex" - "encoding/pem" - "errors" -) - -var ( - oidDataContentType = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 7, 1}) - oidEncryptedDataContentType = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 7, 6}) - - oidFriendlyName = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 9, 20}) - oidLocalKeyID = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 9, 21}) - oidMicrosoftCSPName = asn1.ObjectIdentifier([]int{1, 3, 6, 1, 4, 1, 311, 17, 1}) -) - -type pfxPdu struct { - Version int - AuthSafe contentInfo - MacData macData `asn1:"optional"` -} - -type contentInfo struct { - ContentType asn1.ObjectIdentifier - Content asn1.RawValue `asn1:"tag:0,explicit,optional"` -} - -type encryptedData struct { - Version int - EncryptedContentInfo encryptedContentInfo -} - -type encryptedContentInfo struct { - ContentType asn1.ObjectIdentifier - ContentEncryptionAlgorithm pkix.AlgorithmIdentifier - EncryptedContent []byte `asn1:"tag:0,optional"` -} - -func (i encryptedContentInfo) Algorithm() pkix.AlgorithmIdentifier { - return i.ContentEncryptionAlgorithm -} - -func (i encryptedContentInfo) Data() []byte { return i.EncryptedContent } - -type safeBag struct { - Id asn1.ObjectIdentifier - Value asn1.RawValue `asn1:"tag:0,explicit"` - Attributes []pkcs12Attribute `asn1:"set,optional"` -} - -type pkcs12Attribute struct { - Id asn1.ObjectIdentifier - Value asn1.RawValue `ans1:"set"` -} - -type encryptedPrivateKeyInfo struct { - AlgorithmIdentifier pkix.AlgorithmIdentifier - EncryptedData []byte -} - -func (i encryptedPrivateKeyInfo) Algorithm() pkix.AlgorithmIdentifier { - return i.AlgorithmIdentifier -} - -func (i encryptedPrivateKeyInfo) Data() []byte { - return i.EncryptedData -} - -// PEM block types -const ( - certificateType = "CERTIFICATE" - privateKeyType = "PRIVATE KEY" -) - -// unmarshal calls asn1.Unmarshal, but also returns an error if there is any -// trailing data after unmarshaling. -func unmarshal(in []byte, out interface{}) error { - trailing, err := asn1.Unmarshal(in, out) - if err != nil { - return err - } - if len(trailing) != 0 { - return errors.New("pkcs12: trailing data found") - } - return nil -} - -// ConvertToPEM converts all "safe bags" contained in pfxData to PEM blocks. -func ToPEM(pfxData []byte, password string) ([]*pem.Block, error) { - encodedPassword, err := bmpString(password) - if err != nil { - return nil, ErrIncorrectPassword - } - - bags, encodedPassword, err := getSafeContents(pfxData, encodedPassword) - - blocks := make([]*pem.Block, 0, len(bags)) - for _, bag := range bags { - block, err := convertBag(&bag, encodedPassword) - if err != nil { - return nil, err - } - blocks = append(blocks, block) - } - - return blocks, nil -} - -func convertBag(bag *safeBag, password []byte) (*pem.Block, error) { - block := &pem.Block{ - Headers: make(map[string]string), - } - - for _, attribute := range bag.Attributes { - k, v, err := convertAttribute(&attribute) - if err != nil { - return nil, err - } - block.Headers[k] = v - } - - switch { - case bag.Id.Equal(oidCertBag): - block.Type = certificateType - certsData, err := decodeCertBag(bag.Value.Bytes) - if err != nil { - return nil, err - } - block.Bytes = certsData - case bag.Id.Equal(oidPKCS8ShroundedKeyBag): - block.Type = privateKeyType - - key, err := decodePkcs8ShroudedKeyBag(bag.Value.Bytes, password) - if err != nil { - return nil, err - } - - switch key := key.(type) { - case *rsa.PrivateKey: - block.Bytes = x509.MarshalPKCS1PrivateKey(key) - case *ecdsa.PrivateKey: - block.Bytes, err = x509.MarshalECPrivateKey(key) - if err != nil { - return nil, err - } - default: - return nil, errors.New("found unknown private key type in PKCS#8 wrapping") - } - default: - return nil, errors.New("don't know how to convert a safe bag of type " + bag.Id.String()) - } - return block, nil -} - -func convertAttribute(attribute *pkcs12Attribute) (key, value string, err error) { - isString := false - - switch { - case attribute.Id.Equal(oidFriendlyName): - key = "friendlyName" - isString = true - case attribute.Id.Equal(oidLocalKeyID): - key = "localKeyId" - case attribute.Id.Equal(oidMicrosoftCSPName): - // This key is chosen to match OpenSSL. - key = "Microsoft CSP Name" - isString = true - default: - return "", "", errors.New("pkcs12: unknown attribute with OID " + attribute.Id.String()) - } - - if isString { - if err := unmarshal(attribute.Value.Bytes, &attribute.Value); err != nil { - return "", "", err - } - if value, err = decodeBMPString(attribute.Value.Bytes); err != nil { - return "", "", err - } - } else { - var id []byte - if err := unmarshal(attribute.Value.Bytes, &id); err != nil { - return "", "", err - } - value = hex.EncodeToString(id) - } - - return key, value, nil -} - -// Decode extracts a certificate and private key from pfxData. This function -// assumes that there is only one certificate and only one private key in the -// pfxData. -func Decode(pfxData []byte, password string) (privateKey interface{}, certificate *x509.Certificate, err error) { - encodedPassword, err := bmpString(password) - if err != nil { - return nil, nil, err - } - - bags, encodedPassword, err := getSafeContents(pfxData, encodedPassword) - if err != nil { - return nil, nil, err - } - - if len(bags) != 2 { - err = errors.New("pkcs12: expected exactly two safe bags in the PFX PDU") - return - } - - for _, bag := range bags { - switch { - case bag.Id.Equal(oidCertBag): - if certificate != nil { - err = errors.New("pkcs12: expected exactly one certificate bag") - } - - certsData, err := decodeCertBag(bag.Value.Bytes) - if err != nil { - return nil, nil, err - } - certs, err := x509.ParseCertificates(certsData) - if err != nil { - return nil, nil, err - } - if len(certs) != 1 { - err = errors.New("pkcs12: expected exactly one certificate in the certBag") - return nil, nil, err - } - certificate = certs[0] - - case bag.Id.Equal(oidPKCS8ShroundedKeyBag): - if privateKey != nil { - err = errors.New("pkcs12: expected exactly one key bag") - } - - if privateKey, err = decodePkcs8ShroudedKeyBag(bag.Value.Bytes, encodedPassword); err != nil { - return nil, nil, err - } - } - } - - if certificate == nil { - return nil, nil, errors.New("pkcs12: certificate missing") - } - if privateKey == nil { - return nil, nil, errors.New("pkcs12: private key missing") - } - - return -} - -func getSafeContents(p12Data, password []byte) (bags []safeBag, updatedPassword []byte, err error) { - pfx := new(pfxPdu) - if err := unmarshal(p12Data, pfx); err != nil { - return nil, nil, errors.New("pkcs12: error reading P12 data: " + err.Error()) - } - - if pfx.Version != 3 { - return nil, nil, NotImplementedError("can only decode v3 PFX PDU's") - } - - if !pfx.AuthSafe.ContentType.Equal(oidDataContentType) { - return nil, nil, NotImplementedError("only password-protected PFX is implemented") - } - - // unmarshal the explicit bytes in the content for type 'data' - if err := unmarshal(pfx.AuthSafe.Content.Bytes, &pfx.AuthSafe.Content); err != nil { - return nil, nil, err - } - - if len(pfx.MacData.Mac.Algorithm.Algorithm) == 0 { - return nil, nil, errors.New("pkcs12: no MAC in data") - } - - if err := verifyMac(&pfx.MacData, pfx.AuthSafe.Content.Bytes, password); err != nil { - if err == ErrIncorrectPassword && len(password) == 2 && password[0] == 0 && password[1] == 0 { - // some implementations use an empty byte array - // for the empty string password try one more - // time with empty-empty password - password = nil - err = verifyMac(&pfx.MacData, pfx.AuthSafe.Content.Bytes, password) - } - if err != nil { - return nil, nil, err - } - } - - var authenticatedSafe []contentInfo - if err := unmarshal(pfx.AuthSafe.Content.Bytes, &authenticatedSafe); err != nil { - return nil, nil, err - } - - if len(authenticatedSafe) != 2 { - return nil, nil, NotImplementedError("expected exactly two items in the authenticated safe") - } - - for _, ci := range authenticatedSafe { - var data []byte - - switch { - case ci.ContentType.Equal(oidDataContentType): - if err := unmarshal(ci.Content.Bytes, &data); err != nil { - return nil, nil, err - } - case ci.ContentType.Equal(oidEncryptedDataContentType): - var encryptedData encryptedData - if err := unmarshal(ci.Content.Bytes, &encryptedData); err != nil { - return nil, nil, err - } - if encryptedData.Version != 0 { - return nil, nil, NotImplementedError("only version 0 of EncryptedData is supported") - } - if data, err = pbDecrypt(encryptedData.EncryptedContentInfo, password); err != nil { - return nil, nil, err - } - default: - return nil, nil, NotImplementedError("only data and encryptedData content types are supported in authenticated safe") - } - - var safeContents []safeBag - if err := unmarshal(data, &safeContents); err != nil { - return nil, nil, err - } - bags = append(bags, safeContents...) - } - - return bags, password, nil -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/safebags.go b/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/safebags.go deleted file mode 100644 index def1f7b98d7d..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12/safebags.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package pkcs12 - -import ( - "crypto/x509" - "encoding/asn1" - "errors" -) - -var ( - // see https://tools.ietf.org/html/rfc7292#appendix-D - oidCertTypeX509Certificate = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 9, 22, 1}) - oidPKCS8ShroundedKeyBag = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 10, 1, 2}) - oidCertBag = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 10, 1, 3}) -) - -type certBag struct { - Id asn1.ObjectIdentifier - Data []byte `asn1:"tag:0,explicit"` -} - -func decodePkcs8ShroudedKeyBag(asn1Data, password []byte) (privateKey interface{}, err error) { - pkinfo := new(encryptedPrivateKeyInfo) - if err = unmarshal(asn1Data, pkinfo); err != nil { - return nil, errors.New("pkcs12: error decoding PKCS#8 shrouded key bag: " + err.Error()) - } - - pkData, err := pbDecrypt(pkinfo, password) - if err != nil { - return nil, errors.New("pkcs12: error decrypting PKCS#8 shrouded key bag: " + err.Error()) - } - - ret := new(asn1.RawValue) - if err = unmarshal(pkData, ret); err != nil { - return nil, errors.New("pkcs12: error unmarshaling decrypted private key: " + err.Error()) - } - - if privateKey, err = x509.ParsePKCS8PrivateKey(pkData); err != nil { - return nil, errors.New("pkcs12: error parsing PKCS#8 private key: " + err.Error()) - } - - return privateKey, nil -} - -func decodeCertBag(asn1Data []byte) (x509Certificates []byte, err error) { - bag := new(certBag) - if err := unmarshal(asn1Data, bag); err != nil { - return nil, errors.New("pkcs12: error decoding cert bag: " + err.Error()) - } - if !bag.Id.Equal(oidCertTypeX509Certificate) { - return nil, NotImplementedError("only X509 certificates are supported") - } - return bag.Data, nil -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/client.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/client.go index 7b92757093b0..981e67441c83 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/client.go @@ -1,3 +1,9 @@ +// Package cdn implements the Azure ARM Cdn service API version 2015-06-01. +// +// Use these APIs to manage Azure CDN resources through the Azure Resource +// Manager. You must make sure that requests made to these resources are +// secure. For more information, see Authenticating Azure Resource Manager +// requests (https://msdn.microsoft.com/en-us/library/azure/dn790557.aspx). package cdn // Copyright (c) Microsoft and contributors. All rights reserved. @@ -14,12 +20,12 @@ package cdn // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" ) const ( @@ -30,11 +36,7 @@ const ( DefaultBaseURI = "https://management.azure.com" ) -// ManagementClient is the use these APIs to manage Azure CDN resources -// through the Azure Resource Manager. You must make sure that requests made -// to these resources are secure. For more information, see Authenticating -// Azure Resource Manager requests. +// ManagementClient is the base client for Cdn. type ManagementClient struct { autorest.Client BaseURI string diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/customdomains.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/customdomains.go index a81838580b7d..d57065f8e7c7 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/customdomains.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/customdomains.go @@ -14,12 +14,13 @@ package cdn // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -45,35 +46,37 @@ func NewCustomDomainsClientWithBaseURI(baseURI string, subscriptionID string) Cu return CustomDomainsClient{NewWithBaseURI(baseURI, subscriptionID)} } -// Create sends the create request. +// Create sends the create request. This method may poll for completion. +// Polling can be canceled by passing the cancel channel argument. The +// channel will be used to cancel polling and any outstanding HTTP requests. // // customDomainName is name of the custom domain within an endpoint // customDomainProperties is custom domain properties required for creation // endpointName is name of the endpoint within the CDN profile profileName is // name of the CDN profile within the resource group resourceGroupName is // name of the resource group within the Azure subscription -func (client CustomDomainsClient) Create(customDomainName string, customDomainProperties CustomDomainParameters, endpointName string, profileName string, resourceGroupName string) (result CustomDomain, ae error) { - req, err := client.CreatePreparer(customDomainName, customDomainProperties, endpointName, profileName, resourceGroupName) +func (client CustomDomainsClient) Create(customDomainName string, customDomainProperties CustomDomainParameters, endpointName string, profileName string, resourceGroupName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreatePreparer(customDomainName, customDomainProperties, endpointName, profileName, resourceGroupName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "cdn/CustomDomainsClient", "Create", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "cdn.CustomDomainsClient", "Create", nil, "Failure preparing request") } resp, err := client.CreateSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "cdn/CustomDomainsClient", "Create", resp.StatusCode, "Failure sending request") + result.Response = resp + return result, autorest.NewErrorWithError(err, "cdn.CustomDomainsClient", "Create", resp, "Failure sending request") } result, err = client.CreateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "cdn/CustomDomainsClient", "Create", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "cdn.CustomDomainsClient", "Create", resp, "Failure responding to request") } return } // CreatePreparer prepares the Create request. -func (client CustomDomainsClient) CreatePreparer(customDomainName string, customDomainProperties CustomDomainParameters, endpointName string, profileName string, resourceGroupName string) (*http.Request, error) { +func (client CustomDomainsClient) CreatePreparer(customDomainName string, customDomainProperties CustomDomainParameters, endpointName string, profileName string, resourceGroupName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "customDomainName": url.QueryEscape(customDomainName), "endpointName": url.QueryEscape(endpointName), @@ -86,7 +89,7 @@ func (client CustomDomainsClient) CreatePreparer(customDomainName string, custom "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), @@ -99,50 +102,54 @@ func (client CustomDomainsClient) CreatePreparer(customDomainName string, custom // CreateSender sends the Create request. The method will close the // http.Response Body if it receives an error. func (client CustomDomainsClient) CreateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusCreated, http.StatusAccepted) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // CreateResponder handles the response to the Create request. The method always // closes the http.Response Body. -func (client CustomDomainsClient) CreateResponder(resp *http.Response) (result CustomDomain, err error) { +func (client CustomDomainsClient) CreateResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + result.Response = resp return } -// DeleteIfExists sends the delete if exists request. +// DeleteIfExists sends the delete if exists request. This method may poll for +// completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. // // customDomainName is name of the custom domain within an endpoint // endpointName is name of the endpoint within the CDN profile profileName is // name of the CDN profile within the resource group resourceGroupName is // name of the resource group within the Azure subscription -func (client CustomDomainsClient) DeleteIfExists(customDomainName string, endpointName string, profileName string, resourceGroupName string) (result CustomDomain, ae error) { - req, err := client.DeleteIfExistsPreparer(customDomainName, endpointName, profileName, resourceGroupName) +func (client CustomDomainsClient) DeleteIfExists(customDomainName string, endpointName string, profileName string, resourceGroupName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeleteIfExistsPreparer(customDomainName, endpointName, profileName, resourceGroupName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "cdn/CustomDomainsClient", "DeleteIfExists", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "cdn.CustomDomainsClient", "DeleteIfExists", nil, "Failure preparing request") } resp, err := client.DeleteIfExistsSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "cdn/CustomDomainsClient", "DeleteIfExists", resp.StatusCode, "Failure sending request") + result.Response = resp + return result, autorest.NewErrorWithError(err, "cdn.CustomDomainsClient", "DeleteIfExists", resp, "Failure sending request") } result, err = client.DeleteIfExistsResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "cdn/CustomDomainsClient", "DeleteIfExists", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "cdn.CustomDomainsClient", "DeleteIfExists", resp, "Failure responding to request") } return } // DeleteIfExistsPreparer prepares the DeleteIfExists request. -func (client CustomDomainsClient) DeleteIfExistsPreparer(customDomainName string, endpointName string, profileName string, resourceGroupName string) (*http.Request, error) { +func (client CustomDomainsClient) DeleteIfExistsPreparer(customDomainName string, endpointName string, profileName string, resourceGroupName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "customDomainName": url.QueryEscape(customDomainName), "endpointName": url.QueryEscape(endpointName), @@ -155,7 +162,7 @@ func (client CustomDomainsClient) DeleteIfExistsPreparer(customDomainName string "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), @@ -167,19 +174,20 @@ func (client CustomDomainsClient) DeleteIfExistsPreparer(customDomainName string // DeleteIfExistsSender sends the DeleteIfExists request. The method will close the // http.Response Body if it receives an error. func (client CustomDomainsClient) DeleteIfExistsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted, http.StatusNoContent) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // DeleteIfExistsResponder handles the response to the DeleteIfExists request. The method always // closes the http.Response Body. -func (client CustomDomainsClient) DeleteIfExistsResponder(resp *http.Response) (result CustomDomain, err error) { +func (client CustomDomainsClient) DeleteIfExistsResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByUnmarshallingJSON(&result), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + result.Response = resp return } @@ -189,21 +197,21 @@ func (client CustomDomainsClient) DeleteIfExistsResponder(resp *http.Response) ( // endpointName is name of the endpoint within the CDN profile profileName is // name of the CDN profile within the resource group resourceGroupName is // name of the resource group within the Azure subscription -func (client CustomDomainsClient) Get(customDomainName string, endpointName string, profileName string, resourceGroupName string) (result CustomDomain, ae error) { +func (client CustomDomainsClient) Get(customDomainName string, endpointName string, profileName string, resourceGroupName string) (result CustomDomain, err error) { req, err := client.GetPreparer(customDomainName, endpointName, profileName, resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "cdn/CustomDomainsClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "cdn.CustomDomainsClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "cdn/CustomDomainsClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "cdn.CustomDomainsClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "cdn/CustomDomainsClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "cdn.CustomDomainsClient", "Get", resp, "Failure responding to request") } return @@ -235,7 +243,7 @@ func (client CustomDomainsClient) GetPreparer(customDomainName string, endpointN // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client CustomDomainsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -244,7 +252,7 @@ func (client CustomDomainsClient) GetResponder(resp *http.Response) (result Cust err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -256,21 +264,21 @@ func (client CustomDomainsClient) GetResponder(resp *http.Response) (result Cust // endpointName is name of the endpoint within the CDN profile profileName is // name of the CDN profile within the resource group resourceGroupName is // name of the resource group within the Azure subscription -func (client CustomDomainsClient) ListByEndpoint(endpointName string, profileName string, resourceGroupName string) (result CustomDomainListResult, ae error) { +func (client CustomDomainsClient) ListByEndpoint(endpointName string, profileName string, resourceGroupName string) (result CustomDomainListResult, err error) { req, err := client.ListByEndpointPreparer(endpointName, profileName, resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "cdn/CustomDomainsClient", "ListByEndpoint", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "cdn.CustomDomainsClient", "ListByEndpoint", nil, "Failure preparing request") } resp, err := client.ListByEndpointSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "cdn/CustomDomainsClient", "ListByEndpoint", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "cdn.CustomDomainsClient", "ListByEndpoint", resp, "Failure sending request") } result, err = client.ListByEndpointResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "cdn/CustomDomainsClient", "ListByEndpoint", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "cdn.CustomDomainsClient", "ListByEndpoint", resp, "Failure responding to request") } return @@ -301,7 +309,7 @@ func (client CustomDomainsClient) ListByEndpointPreparer(endpointName string, pr // ListByEndpointSender sends the ListByEndpoint request. The method will close the // http.Response Body if it receives an error. func (client CustomDomainsClient) ListByEndpointSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListByEndpointResponder handles the response to the ListByEndpoint request. The method always @@ -310,7 +318,7 @@ func (client CustomDomainsClient) ListByEndpointResponder(resp *http.Response) ( err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -324,21 +332,21 @@ func (client CustomDomainsClient) ListByEndpointResponder(resp *http.Response) ( // is name of the endpoint within the CDN profile profileName is name of the // CDN profile within the resource group resourceGroupName is name of the // resource group within the Azure subscription -func (client CustomDomainsClient) Update(customDomainName string, customDomainProperties CustomDomainParameters, endpointName string, profileName string, resourceGroupName string) (result ErrorResponse, ae error) { +func (client CustomDomainsClient) Update(customDomainName string, customDomainProperties CustomDomainParameters, endpointName string, profileName string, resourceGroupName string) (result ErrorResponse, err error) { req, err := client.UpdatePreparer(customDomainName, customDomainProperties, endpointName, profileName, resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "cdn/CustomDomainsClient", "Update", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "cdn.CustomDomainsClient", "Update", nil, "Failure preparing request") } resp, err := client.UpdateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "cdn/CustomDomainsClient", "Update", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "cdn.CustomDomainsClient", "Update", resp, "Failure sending request") } result, err = client.UpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "cdn/CustomDomainsClient", "Update", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "cdn.CustomDomainsClient", "Update", resp, "Failure responding to request") } return @@ -371,7 +379,7 @@ func (client CustomDomainsClient) UpdatePreparer(customDomainName string, custom // UpdateSender sends the Update request. The method will close the // http.Response Body if it receives an error. func (client CustomDomainsClient) UpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // UpdateResponder handles the response to the Update request. The method always @@ -380,7 +388,7 @@ func (client CustomDomainsClient) UpdateResponder(resp *http.Response) (result E err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/endpoints.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/endpoints.go index 57658911be70..7ece144d14a8 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/endpoints.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/endpoints.go @@ -14,12 +14,13 @@ package cdn // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -44,34 +45,36 @@ func NewEndpointsClientWithBaseURI(baseURI string, subscriptionID string) Endpoi return EndpointsClient{NewWithBaseURI(baseURI, subscriptionID)} } -// Create sends the create request. +// Create sends the create request. This method may poll for completion. +// Polling can be canceled by passing the cancel channel argument. The +// channel will be used to cancel polling and any outstanding HTTP requests. // // endpointName is name of the endpoint within the CDN profile // endpointProperties is endpoint properties profileName is name of the CDN // profile within the resource group resourceGroupName is name of the // resource group within the Azure subscription -func (client EndpointsClient) Create(endpointName string, endpointProperties EndpointCreateParameters, profileName string, resourceGroupName string) (result TrackedResource, ae error) { - req, err := client.CreatePreparer(endpointName, endpointProperties, profileName, resourceGroupName) +func (client EndpointsClient) Create(endpointName string, endpointProperties EndpointCreateParameters, profileName string, resourceGroupName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreatePreparer(endpointName, endpointProperties, profileName, resourceGroupName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "cdn/EndpointsClient", "Create", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "cdn.EndpointsClient", "Create", nil, "Failure preparing request") } resp, err := client.CreateSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "cdn/EndpointsClient", "Create", resp.StatusCode, "Failure sending request") + result.Response = resp + return result, autorest.NewErrorWithError(err, "cdn.EndpointsClient", "Create", resp, "Failure sending request") } result, err = client.CreateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "cdn/EndpointsClient", "Create", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "cdn.EndpointsClient", "Create", resp, "Failure responding to request") } return } // CreatePreparer prepares the Create request. -func (client EndpointsClient) CreatePreparer(endpointName string, endpointProperties EndpointCreateParameters, profileName string, resourceGroupName string) (*http.Request, error) { +func (client EndpointsClient) CreatePreparer(endpointName string, endpointProperties EndpointCreateParameters, profileName string, resourceGroupName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "endpointName": url.QueryEscape(endpointName), "profileName": url.QueryEscape(profileName), @@ -83,7 +86,7 @@ func (client EndpointsClient) CreatePreparer(endpointName string, endpointProper "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), @@ -96,49 +99,53 @@ func (client EndpointsClient) CreatePreparer(endpointName string, endpointProper // CreateSender sends the Create request. The method will close the // http.Response Body if it receives an error. func (client EndpointsClient) CreateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusCreated, http.StatusAccepted) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // CreateResponder handles the response to the Create request. The method always // closes the http.Response Body. -func (client EndpointsClient) CreateResponder(resp *http.Response) (result TrackedResource, err error) { +func (client EndpointsClient) CreateResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + result.Response = resp return } -// DeleteIfExists sends the delete if exists request. +// DeleteIfExists sends the delete if exists request. This method may poll for +// completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. // // endpointName is name of the endpoint within the CDN profile profileName is // name of the CDN profile within the resource group resourceGroupName is // name of the resource group within the Azure subscription -func (client EndpointsClient) DeleteIfExists(endpointName string, profileName string, resourceGroupName string) (result autorest.Response, ae error) { - req, err := client.DeleteIfExistsPreparer(endpointName, profileName, resourceGroupName) +func (client EndpointsClient) DeleteIfExists(endpointName string, profileName string, resourceGroupName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeleteIfExistsPreparer(endpointName, profileName, resourceGroupName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "cdn/EndpointsClient", "DeleteIfExists", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "cdn.EndpointsClient", "DeleteIfExists", nil, "Failure preparing request") } resp, err := client.DeleteIfExistsSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "cdn/EndpointsClient", "DeleteIfExists", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "cdn.EndpointsClient", "DeleteIfExists", resp, "Failure sending request") } result, err = client.DeleteIfExistsResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "cdn/EndpointsClient", "DeleteIfExists", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "cdn.EndpointsClient", "DeleteIfExists", resp, "Failure responding to request") } return } // DeleteIfExistsPreparer prepares the DeleteIfExists request. -func (client EndpointsClient) DeleteIfExistsPreparer(endpointName string, profileName string, resourceGroupName string) (*http.Request, error) { +func (client EndpointsClient) DeleteIfExistsPreparer(endpointName string, profileName string, resourceGroupName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "endpointName": url.QueryEscape(endpointName), "profileName": url.QueryEscape(profileName), @@ -150,7 +157,7 @@ func (client EndpointsClient) DeleteIfExistsPreparer(endpointName string, profil "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), @@ -162,7 +169,9 @@ func (client EndpointsClient) DeleteIfExistsPreparer(endpointName string, profil // DeleteIfExistsSender sends the DeleteIfExists request. The method will close the // http.Response Body if it receives an error. func (client EndpointsClient) DeleteIfExistsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted, http.StatusNoContent) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // DeleteIfExistsResponder handles the response to the DeleteIfExists request. The method always @@ -171,7 +180,7 @@ func (client EndpointsClient) DeleteIfExistsResponder(resp *http.Response) (resu err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return @@ -182,21 +191,21 @@ func (client EndpointsClient) DeleteIfExistsResponder(resp *http.Response) (resu // endpointName is name of the endpoint within the CDN profile profileName is // name of the CDN profile within the resource group resourceGroupName is // name of the resource group within the Azure subscription -func (client EndpointsClient) Get(endpointName string, profileName string, resourceGroupName string) (result Endpoint, ae error) { +func (client EndpointsClient) Get(endpointName string, profileName string, resourceGroupName string) (result Endpoint, err error) { req, err := client.GetPreparer(endpointName, profileName, resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "cdn/EndpointsClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "cdn.EndpointsClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "cdn/EndpointsClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "cdn.EndpointsClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "cdn/EndpointsClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "cdn.EndpointsClient", "Get", resp, "Failure responding to request") } return @@ -227,7 +236,7 @@ func (client EndpointsClient) GetPreparer(endpointName string, profileName strin // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client EndpointsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -236,7 +245,7 @@ func (client EndpointsClient) GetResponder(resp *http.Response) (result Endpoint err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -248,21 +257,21 @@ func (client EndpointsClient) GetResponder(resp *http.Response) (result Endpoint // profileName is name of the CDN profile within the resource group // resourceGroupName is name of the resource group within the Azure // subscription -func (client EndpointsClient) ListByProfile(profileName string, resourceGroupName string) (result EndpointListResult, ae error) { +func (client EndpointsClient) ListByProfile(profileName string, resourceGroupName string) (result EndpointListResult, err error) { req, err := client.ListByProfilePreparer(profileName, resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "cdn/EndpointsClient", "ListByProfile", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "cdn.EndpointsClient", "ListByProfile", nil, "Failure preparing request") } resp, err := client.ListByProfileSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "cdn/EndpointsClient", "ListByProfile", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "cdn.EndpointsClient", "ListByProfile", resp, "Failure sending request") } result, err = client.ListByProfileResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "cdn/EndpointsClient", "ListByProfile", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "cdn.EndpointsClient", "ListByProfile", resp, "Failure responding to request") } return @@ -292,7 +301,7 @@ func (client EndpointsClient) ListByProfilePreparer(profileName string, resource // ListByProfileSender sends the ListByProfile request. The method will close the // http.Response Body if it receives an error. func (client EndpointsClient) ListByProfileSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListByProfileResponder handles the response to the ListByProfile request. The method always @@ -301,42 +310,45 @@ func (client EndpointsClient) ListByProfileResponder(resp *http.Response) (resul err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } -// LoadContent sends the load content request. +// LoadContent sends the load content request. This method may poll for +// completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. // // endpointName is name of the endpoint within the CDN profile // contentFilePaths is the path to the content to be loaded. Path should // describe a file. profileName is name of the CDN profile within the // resource group resourceGroupName is name of the resource group within the // Azure subscription -func (client EndpointsClient) LoadContent(endpointName string, contentFilePaths LoadParameters, profileName string, resourceGroupName string) (result autorest.Response, ae error) { - req, err := client.LoadContentPreparer(endpointName, contentFilePaths, profileName, resourceGroupName) +func (client EndpointsClient) LoadContent(endpointName string, contentFilePaths LoadParameters, profileName string, resourceGroupName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.LoadContentPreparer(endpointName, contentFilePaths, profileName, resourceGroupName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "cdn/EndpointsClient", "LoadContent", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "cdn.EndpointsClient", "LoadContent", nil, "Failure preparing request") } resp, err := client.LoadContentSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "cdn/EndpointsClient", "LoadContent", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "cdn.EndpointsClient", "LoadContent", resp, "Failure sending request") } result, err = client.LoadContentResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "cdn/EndpointsClient", "LoadContent", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "cdn.EndpointsClient", "LoadContent", resp, "Failure responding to request") } return } // LoadContentPreparer prepares the LoadContent request. -func (client EndpointsClient) LoadContentPreparer(endpointName string, contentFilePaths LoadParameters, profileName string, resourceGroupName string) (*http.Request, error) { +func (client EndpointsClient) LoadContentPreparer(endpointName string, contentFilePaths LoadParameters, profileName string, resourceGroupName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "endpointName": url.QueryEscape(endpointName), "profileName": url.QueryEscape(profileName), @@ -348,7 +360,7 @@ func (client EndpointsClient) LoadContentPreparer(endpointName string, contentFi "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), @@ -361,7 +373,9 @@ func (client EndpointsClient) LoadContentPreparer(endpointName string, contentFi // LoadContentSender sends the LoadContent request. The method will close the // http.Response Body if it receives an error. func (client EndpointsClient) LoadContentSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // LoadContentResponder handles the response to the LoadContent request. The method always @@ -370,41 +384,44 @@ func (client EndpointsClient) LoadContentResponder(resp *http.Response) (result err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } -// PurgeContent sends the purge content request. +// PurgeContent sends the purge content request. This method may poll for +// completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. // // endpointName is name of the endpoint within the CDN profile // contentFilePaths is the path to the content to be purged. Path can // describe a file or directory. profileName is name of the CDN profile // within the resource group resourceGroupName is name of the resource group // within the Azure subscription -func (client EndpointsClient) PurgeContent(endpointName string, contentFilePaths PurgeParameters, profileName string, resourceGroupName string) (result autorest.Response, ae error) { - req, err := client.PurgeContentPreparer(endpointName, contentFilePaths, profileName, resourceGroupName) +func (client EndpointsClient) PurgeContent(endpointName string, contentFilePaths PurgeParameters, profileName string, resourceGroupName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.PurgeContentPreparer(endpointName, contentFilePaths, profileName, resourceGroupName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "cdn/EndpointsClient", "PurgeContent", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "cdn.EndpointsClient", "PurgeContent", nil, "Failure preparing request") } resp, err := client.PurgeContentSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "cdn/EndpointsClient", "PurgeContent", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "cdn.EndpointsClient", "PurgeContent", resp, "Failure sending request") } result, err = client.PurgeContentResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "cdn/EndpointsClient", "PurgeContent", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "cdn.EndpointsClient", "PurgeContent", resp, "Failure responding to request") } return } // PurgeContentPreparer prepares the PurgeContent request. -func (client EndpointsClient) PurgeContentPreparer(endpointName string, contentFilePaths PurgeParameters, profileName string, resourceGroupName string) (*http.Request, error) { +func (client EndpointsClient) PurgeContentPreparer(endpointName string, contentFilePaths PurgeParameters, profileName string, resourceGroupName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "endpointName": url.QueryEscape(endpointName), "profileName": url.QueryEscape(profileName), @@ -416,7 +433,7 @@ func (client EndpointsClient) PurgeContentPreparer(endpointName string, contentF "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), @@ -429,7 +446,9 @@ func (client EndpointsClient) PurgeContentPreparer(endpointName string, contentF // PurgeContentSender sends the PurgeContent request. The method will close the // http.Response Body if it receives an error. func (client EndpointsClient) PurgeContentSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // PurgeContentResponder handles the response to the PurgeContent request. The method always @@ -438,39 +457,41 @@ func (client EndpointsClient) PurgeContentResponder(resp *http.Response) (result err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } -// Start sends the start request. +// Start sends the start request. This method may poll for completion. Polling +// can be canceled by passing the cancel channel argument. The channel will +// be used to cancel polling and any outstanding HTTP requests. // // endpointName is name of the endpoint within the CDN profile profileName is // name of the CDN profile within the resource group resourceGroupName is // name of the resource group within the Azure subscription -func (client EndpointsClient) Start(endpointName string, profileName string, resourceGroupName string) (result autorest.Response, ae error) { - req, err := client.StartPreparer(endpointName, profileName, resourceGroupName) +func (client EndpointsClient) Start(endpointName string, profileName string, resourceGroupName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.StartPreparer(endpointName, profileName, resourceGroupName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "cdn/EndpointsClient", "Start", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "cdn.EndpointsClient", "Start", nil, "Failure preparing request") } resp, err := client.StartSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "cdn/EndpointsClient", "Start", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "cdn.EndpointsClient", "Start", resp, "Failure sending request") } result, err = client.StartResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "cdn/EndpointsClient", "Start", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "cdn.EndpointsClient", "Start", resp, "Failure responding to request") } return } // StartPreparer prepares the Start request. -func (client EndpointsClient) StartPreparer(endpointName string, profileName string, resourceGroupName string) (*http.Request, error) { +func (client EndpointsClient) StartPreparer(endpointName string, profileName string, resourceGroupName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "endpointName": url.QueryEscape(endpointName), "profileName": url.QueryEscape(profileName), @@ -482,7 +503,7 @@ func (client EndpointsClient) StartPreparer(endpointName string, profileName str "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), @@ -494,7 +515,9 @@ func (client EndpointsClient) StartPreparer(endpointName string, profileName str // StartSender sends the Start request. The method will close the // http.Response Body if it receives an error. func (client EndpointsClient) StartSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // StartResponder handles the response to the Start request. The method always @@ -503,39 +526,41 @@ func (client EndpointsClient) StartResponder(resp *http.Response) (result autore err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } -// Stop sends the stop request. +// Stop sends the stop request. This method may poll for completion. Polling +// can be canceled by passing the cancel channel argument. The channel will +// be used to cancel polling and any outstanding HTTP requests. // // endpointName is name of the endpoint within the CDN profile profileName is // name of the CDN profile within the resource group resourceGroupName is // name of the resource group within the Azure subscription -func (client EndpointsClient) Stop(endpointName string, profileName string, resourceGroupName string) (result autorest.Response, ae error) { - req, err := client.StopPreparer(endpointName, profileName, resourceGroupName) +func (client EndpointsClient) Stop(endpointName string, profileName string, resourceGroupName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.StopPreparer(endpointName, profileName, resourceGroupName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "cdn/EndpointsClient", "Stop", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "cdn.EndpointsClient", "Stop", nil, "Failure preparing request") } resp, err := client.StopSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "cdn/EndpointsClient", "Stop", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "cdn.EndpointsClient", "Stop", resp, "Failure sending request") } result, err = client.StopResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "cdn/EndpointsClient", "Stop", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "cdn.EndpointsClient", "Stop", resp, "Failure responding to request") } return } // StopPreparer prepares the Stop request. -func (client EndpointsClient) StopPreparer(endpointName string, profileName string, resourceGroupName string) (*http.Request, error) { +func (client EndpointsClient) StopPreparer(endpointName string, profileName string, resourceGroupName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "endpointName": url.QueryEscape(endpointName), "profileName": url.QueryEscape(profileName), @@ -547,7 +572,7 @@ func (client EndpointsClient) StopPreparer(endpointName string, profileName stri "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), @@ -559,7 +584,9 @@ func (client EndpointsClient) StopPreparer(endpointName string, profileName stri // StopSender sends the Stop request. The method will close the // http.Response Body if it receives an error. func (client EndpointsClient) StopSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // StopResponder handles the response to the Stop request. The method always @@ -568,7 +595,7 @@ func (client EndpointsClient) StopResponder(resp *http.Response) (result autores err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return @@ -580,21 +607,21 @@ func (client EndpointsClient) StopResponder(resp *http.Response) (result autores // endpointProperties is endpoint properties profileName is name of the CDN // profile within the resource group resourceGroupName is name of the // resource group within the Azure subscription -func (client EndpointsClient) Update(endpointName string, endpointProperties EndpointUpdateParameters, profileName string, resourceGroupName string) (result Endpoint, ae error) { +func (client EndpointsClient) Update(endpointName string, endpointProperties EndpointUpdateParameters, profileName string, resourceGroupName string) (result Endpoint, err error) { req, err := client.UpdatePreparer(endpointName, endpointProperties, profileName, resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "cdn/EndpointsClient", "Update", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "cdn.EndpointsClient", "Update", nil, "Failure preparing request") } resp, err := client.UpdateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "cdn/EndpointsClient", "Update", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "cdn.EndpointsClient", "Update", resp, "Failure sending request") } result, err = client.UpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "cdn/EndpointsClient", "Update", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "cdn.EndpointsClient", "Update", resp, "Failure responding to request") } return @@ -626,7 +653,7 @@ func (client EndpointsClient) UpdatePreparer(endpointName string, endpointProper // UpdateSender sends the Update request. The method will close the // http.Response Body if it receives an error. func (client EndpointsClient) UpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted) + return autorest.SendWithSender(client, req) } // UpdateResponder handles the response to the Update request. The method always @@ -635,7 +662,7 @@ func (client EndpointsClient) UpdateResponder(resp *http.Response) (result Endpo err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -648,21 +675,21 @@ func (client EndpointsClient) UpdateResponder(resp *http.Response) (result Endpo // customDomainProperties is custom domain to validate profileName is name of // the CDN profile within the resource group resourceGroupName is name of the // resource group within the Azure subscription -func (client EndpointsClient) ValidateCustomDomain(endpointName string, customDomainProperties ValidateCustomDomainInput, profileName string, resourceGroupName string) (result ValidateCustomDomainOutput, ae error) { +func (client EndpointsClient) ValidateCustomDomain(endpointName string, customDomainProperties ValidateCustomDomainInput, profileName string, resourceGroupName string) (result ValidateCustomDomainOutput, err error) { req, err := client.ValidateCustomDomainPreparer(endpointName, customDomainProperties, profileName, resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "cdn/EndpointsClient", "ValidateCustomDomain", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "cdn.EndpointsClient", "ValidateCustomDomain", nil, "Failure preparing request") } resp, err := client.ValidateCustomDomainSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "cdn/EndpointsClient", "ValidateCustomDomain", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "cdn.EndpointsClient", "ValidateCustomDomain", resp, "Failure sending request") } result, err = client.ValidateCustomDomainResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "cdn/EndpointsClient", "ValidateCustomDomain", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "cdn.EndpointsClient", "ValidateCustomDomain", resp, "Failure responding to request") } return @@ -694,7 +721,7 @@ func (client EndpointsClient) ValidateCustomDomainPreparer(endpointName string, // ValidateCustomDomainSender sends the ValidateCustomDomain request. The method will close the // http.Response Body if it receives an error. func (client EndpointsClient) ValidateCustomDomainSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ValidateCustomDomainResponder handles the response to the ValidateCustomDomain request. The method always @@ -703,7 +730,7 @@ func (client EndpointsClient) ValidateCustomDomainResponder(resp *http.Response) err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/models.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/models.go index ad3940323d95..f7f0f542c5dd 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/models.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/models.go @@ -14,12 +14,12 @@ package cdn // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" ) // CustomDomainResourceState enumerates the values for custom domain resource @@ -118,6 +118,8 @@ const ( // IgnoreQueryString specifies the ignore query string state for query // string caching behavior. IgnoreQueryString QueryStringCachingBehavior = "IgnoreQueryString" + // NotSet specifies the not set state for query string caching behavior. + NotSet QueryStringCachingBehavior = "NotSet" // UseQueryString specifies the use query string state for query string // caching behavior. UseQueryString QueryStringCachingBehavior = "UseQueryString" @@ -201,8 +203,8 @@ type DeepCreatedOrigin struct { // endpoint type DeepCreatedOriginProperties struct { HostName *string `json:"hostName,omitempty"` - HTTPPort *int `json:"httpPort,omitempty"` - HTTPSPort *int `json:"httpsPort,omitempty"` + HTTPPort *int32 `json:"httpPort,omitempty"` + HTTPSPort *int32 `json:"httpsPort,omitempty"` } // Endpoint is cDN Endpoint is the entity within a CDN Profile containing @@ -324,8 +326,8 @@ type OriginParameters struct { // OriginProperties is type OriginProperties struct { HostName *string `json:"hostName,omitempty"` - HTTPPort *int `json:"httpPort,omitempty"` - HTTPSPort *int `json:"httpsPort,omitempty"` + HTTPPort *int32 `json:"httpPort,omitempty"` + HTTPSPort *int32 `json:"httpsPort,omitempty"` ResourceState OriginResourceState `json:"resourceState,omitempty"` ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` } @@ -333,8 +335,8 @@ type OriginProperties struct { // OriginPropertiesParameters is type OriginPropertiesParameters struct { HostName *string `json:"hostName,omitempty"` - HTTPPort *int `json:"httpPort,omitempty"` - HTTPSPort *int `json:"httpsPort,omitempty"` + HTTPPort *int32 `json:"httpPort,omitempty"` + HTTPSPort *int32 `json:"httpsPort,omitempty"` } // Profile is cDN profile represents the top level resource and the entry @@ -406,12 +408,11 @@ type SsoURI struct { // TrackedResource is aRM tracked resource type TrackedResource struct { - autorest.Response `json:"-"` - ID *string `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - Type *string `json:"type,omitempty"` - Location *string `json:"location,omitempty"` - Tags *map[string]*string `json:"tags,omitempty"` + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` } // ValidateCustomDomainInput is input of the custom domain to be validated diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/nameavailability.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/nameavailability.go index 4da9228cc405..4f479d47ba41 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/nameavailability.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/nameavailability.go @@ -14,12 +14,13 @@ package cdn // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" ) @@ -47,21 +48,21 @@ func NewNameAvailabilityClientWithBaseURI(baseURI string, subscriptionID string) // CheckNameAvailability sends the check name availability request. // // checkNameAvailabilityInput is input to check -func (client NameAvailabilityClient) CheckNameAvailability(checkNameAvailabilityInput CheckNameAvailabilityInput) (result CheckNameAvailabilityOutput, ae error) { +func (client NameAvailabilityClient) CheckNameAvailability(checkNameAvailabilityInput CheckNameAvailabilityInput) (result CheckNameAvailabilityOutput, err error) { req, err := client.CheckNameAvailabilityPreparer(checkNameAvailabilityInput) if err != nil { - return result, autorest.NewErrorWithError(err, "cdn/NameAvailabilityClient", "CheckNameAvailability", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "cdn.NameAvailabilityClient", "CheckNameAvailability", nil, "Failure preparing request") } resp, err := client.CheckNameAvailabilitySender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "cdn/NameAvailabilityClient", "CheckNameAvailability", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "cdn.NameAvailabilityClient", "CheckNameAvailability", resp, "Failure sending request") } result, err = client.CheckNameAvailabilityResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "cdn/NameAvailabilityClient", "CheckNameAvailability", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "cdn.NameAvailabilityClient", "CheckNameAvailability", resp, "Failure responding to request") } return @@ -85,7 +86,7 @@ func (client NameAvailabilityClient) CheckNameAvailabilityPreparer(checkNameAvai // CheckNameAvailabilitySender sends the CheckNameAvailability request. The method will close the // http.Response Body if it receives an error. func (client NameAvailabilityClient) CheckNameAvailabilitySender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // CheckNameAvailabilityResponder handles the response to the CheckNameAvailability request. The method always @@ -94,7 +95,7 @@ func (client NameAvailabilityClient) CheckNameAvailabilityResponder(resp *http.R err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/operations.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/operations.go index ac2e33f582f5..38d80ede37d8 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/operations.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/operations.go @@ -14,12 +14,13 @@ package cdn // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" ) @@ -44,21 +45,21 @@ func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) Opera } // List sends the list request. -func (client OperationsClient) List() (result OperationListResult, ae error) { +func (client OperationsClient) List() (result OperationListResult, err error) { req, err := client.ListPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "cdn/OperationsClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "cdn.OperationsClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "cdn/OperationsClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "cdn.OperationsClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "cdn/OperationsClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "cdn.OperationsClient", "List", resp, "Failure responding to request") } return @@ -81,7 +82,7 @@ func (client OperationsClient) ListPreparer() (*http.Request, error) { // 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 client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -90,7 +91,7 @@ func (client OperationsClient) ListResponder(resp *http.Response) (result Operat err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/origins.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/origins.go index 9bf1ddc74ff0..edeba7967c72 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/origins.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/origins.go @@ -14,12 +14,13 @@ package cdn // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -43,35 +44,37 @@ func NewOriginsClientWithBaseURI(baseURI string, subscriptionID string) OriginsC return OriginsClient{NewWithBaseURI(baseURI, subscriptionID)} } -// Create sends the create request. +// Create sends the create request. This method may poll for completion. +// Polling can be canceled by passing the cancel channel argument. The +// channel will be used to cancel polling and any outstanding HTTP requests. // // originName is name of the origin, an arbitrary value but it needs to be // unique under endpoint originProperties is origin properties endpointName // is name of the endpoint within the CDN profile profileName is name of the // CDN profile within the resource group resourceGroupName is name of the // resource group within the Azure subscription -func (client OriginsClient) Create(originName string, originProperties OriginParameters, endpointName string, profileName string, resourceGroupName string) (result Origin, ae error) { - req, err := client.CreatePreparer(originName, originProperties, endpointName, profileName, resourceGroupName) +func (client OriginsClient) Create(originName string, originProperties OriginParameters, endpointName string, profileName string, resourceGroupName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreatePreparer(originName, originProperties, endpointName, profileName, resourceGroupName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "cdn/OriginsClient", "Create", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "cdn.OriginsClient", "Create", nil, "Failure preparing request") } resp, err := client.CreateSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "cdn/OriginsClient", "Create", resp.StatusCode, "Failure sending request") + result.Response = resp + return result, autorest.NewErrorWithError(err, "cdn.OriginsClient", "Create", resp, "Failure sending request") } result, err = client.CreateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "cdn/OriginsClient", "Create", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "cdn.OriginsClient", "Create", resp, "Failure responding to request") } return } // CreatePreparer prepares the Create request. -func (client OriginsClient) CreatePreparer(originName string, originProperties OriginParameters, endpointName string, profileName string, resourceGroupName string) (*http.Request, error) { +func (client OriginsClient) CreatePreparer(originName string, originProperties OriginParameters, endpointName string, profileName string, resourceGroupName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "endpointName": url.QueryEscape(endpointName), "originName": url.QueryEscape(originName), @@ -84,7 +87,7 @@ func (client OriginsClient) CreatePreparer(originName string, originProperties O "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), @@ -97,51 +100,55 @@ func (client OriginsClient) CreatePreparer(originName string, originProperties O // CreateSender sends the Create request. The method will close the // http.Response Body if it receives an error. func (client OriginsClient) CreateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusCreated, http.StatusAccepted) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // CreateResponder handles the response to the Create request. The method always // closes the http.Response Body. -func (client OriginsClient) CreateResponder(resp *http.Response) (result Origin, err error) { +func (client OriginsClient) CreateResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + result.Response = resp return } -// DeleteIfExists sends the delete if exists request. +// DeleteIfExists sends the delete if exists request. This method may poll for +// completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. // // originName is name of the origin, an arbitrary value but it needs to be // unique under endpoint endpointName is name of the endpoint within the CDN // profile profileName is name of the CDN profile within the resource group // resourceGroupName is name of the resource group within the Azure // subscription -func (client OriginsClient) DeleteIfExists(originName string, endpointName string, profileName string, resourceGroupName string) (result Origin, ae error) { - req, err := client.DeleteIfExistsPreparer(originName, endpointName, profileName, resourceGroupName) +func (client OriginsClient) DeleteIfExists(originName string, endpointName string, profileName string, resourceGroupName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeleteIfExistsPreparer(originName, endpointName, profileName, resourceGroupName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "cdn/OriginsClient", "DeleteIfExists", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "cdn.OriginsClient", "DeleteIfExists", nil, "Failure preparing request") } resp, err := client.DeleteIfExistsSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "cdn/OriginsClient", "DeleteIfExists", resp.StatusCode, "Failure sending request") + result.Response = resp + return result, autorest.NewErrorWithError(err, "cdn.OriginsClient", "DeleteIfExists", resp, "Failure sending request") } result, err = client.DeleteIfExistsResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "cdn/OriginsClient", "DeleteIfExists", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "cdn.OriginsClient", "DeleteIfExists", resp, "Failure responding to request") } return } // DeleteIfExistsPreparer prepares the DeleteIfExists request. -func (client OriginsClient) DeleteIfExistsPreparer(originName string, endpointName string, profileName string, resourceGroupName string) (*http.Request, error) { +func (client OriginsClient) DeleteIfExistsPreparer(originName string, endpointName string, profileName string, resourceGroupName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "endpointName": url.QueryEscape(endpointName), "originName": url.QueryEscape(originName), @@ -154,7 +161,7 @@ func (client OriginsClient) DeleteIfExistsPreparer(originName string, endpointNa "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), @@ -166,19 +173,20 @@ func (client OriginsClient) DeleteIfExistsPreparer(originName string, endpointNa // DeleteIfExistsSender sends the DeleteIfExists request. The method will close the // http.Response Body if it receives an error. func (client OriginsClient) DeleteIfExistsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted, http.StatusNoContent) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // DeleteIfExistsResponder handles the response to the DeleteIfExists request. The method always // closes the http.Response Body. -func (client OriginsClient) DeleteIfExistsResponder(resp *http.Response) (result Origin, err error) { +func (client OriginsClient) DeleteIfExistsResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByUnmarshallingJSON(&result), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + result.Response = resp return } @@ -189,21 +197,21 @@ func (client OriginsClient) DeleteIfExistsResponder(resp *http.Response) (result // profile profileName is name of the CDN profile within the resource group // resourceGroupName is name of the resource group within the Azure // subscription -func (client OriginsClient) Get(originName string, endpointName string, profileName string, resourceGroupName string) (result Origin, ae error) { +func (client OriginsClient) Get(originName string, endpointName string, profileName string, resourceGroupName string) (result Origin, err error) { req, err := client.GetPreparer(originName, endpointName, profileName, resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "cdn/OriginsClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "cdn.OriginsClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "cdn/OriginsClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "cdn.OriginsClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "cdn/OriginsClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "cdn.OriginsClient", "Get", resp, "Failure responding to request") } return @@ -235,7 +243,7 @@ func (client OriginsClient) GetPreparer(originName string, endpointName string, // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client OriginsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -244,7 +252,7 @@ func (client OriginsClient) GetResponder(resp *http.Response) (result Origin, er err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -256,21 +264,21 @@ func (client OriginsClient) GetResponder(resp *http.Response) (result Origin, er // endpointName is name of the endpoint within the CDN profile profileName is // name of the CDN profile within the resource group resourceGroupName is // name of the resource group within the Azure subscription -func (client OriginsClient) ListByEndpoint(endpointName string, profileName string, resourceGroupName string) (result OriginListResult, ae error) { +func (client OriginsClient) ListByEndpoint(endpointName string, profileName string, resourceGroupName string) (result OriginListResult, err error) { req, err := client.ListByEndpointPreparer(endpointName, profileName, resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "cdn/OriginsClient", "ListByEndpoint", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "cdn.OriginsClient", "ListByEndpoint", nil, "Failure preparing request") } resp, err := client.ListByEndpointSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "cdn/OriginsClient", "ListByEndpoint", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "cdn.OriginsClient", "ListByEndpoint", resp, "Failure sending request") } result, err = client.ListByEndpointResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "cdn/OriginsClient", "ListByEndpoint", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "cdn.OriginsClient", "ListByEndpoint", resp, "Failure responding to request") } return @@ -301,7 +309,7 @@ func (client OriginsClient) ListByEndpointPreparer(endpointName string, profileN // ListByEndpointSender sends the ListByEndpoint request. The method will close the // http.Response Body if it receives an error. func (client OriginsClient) ListByEndpointSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListByEndpointResponder handles the response to the ListByEndpoint request. The method always @@ -310,7 +318,7 @@ func (client OriginsClient) ListByEndpointResponder(resp *http.Response) (result err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -324,21 +332,21 @@ func (client OriginsClient) ListByEndpointResponder(resp *http.Response) (result // is name of the endpoint within the CDN profile profileName is name of the // CDN profile within the resource group resourceGroupName is name of the // resource group within the Azure subscription -func (client OriginsClient) Update(originName string, originProperties OriginParameters, endpointName string, profileName string, resourceGroupName string) (result Origin, ae error) { +func (client OriginsClient) Update(originName string, originProperties OriginParameters, endpointName string, profileName string, resourceGroupName string) (result Origin, err error) { req, err := client.UpdatePreparer(originName, originProperties, endpointName, profileName, resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "cdn/OriginsClient", "Update", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "cdn.OriginsClient", "Update", nil, "Failure preparing request") } resp, err := client.UpdateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "cdn/OriginsClient", "Update", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "cdn.OriginsClient", "Update", resp, "Failure sending request") } result, err = client.UpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "cdn/OriginsClient", "Update", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "cdn.OriginsClient", "Update", resp, "Failure responding to request") } return @@ -371,7 +379,7 @@ func (client OriginsClient) UpdatePreparer(originName string, originProperties O // UpdateSender sends the Update request. The method will close the // http.Response Body if it receives an error. func (client OriginsClient) UpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted) + return autorest.SendWithSender(client, req) } // UpdateResponder handles the response to the Update request. The method always @@ -380,7 +388,7 @@ func (client OriginsClient) UpdateResponder(resp *http.Response) (result Origin, err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/profiles.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/profiles.go index 10b73e027876..9f37d2a0e9c5 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/profiles.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/profiles.go @@ -14,12 +14,13 @@ package cdn // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -44,34 +45,36 @@ func NewProfilesClientWithBaseURI(baseURI string, subscriptionID string) Profile return ProfilesClient{NewWithBaseURI(baseURI, subscriptionID)} } -// Create sends the create request. +// Create sends the create request. This method may poll for completion. +// Polling can be canceled by passing the cancel channel argument. The +// channel will be used to cancel polling and any outstanding HTTP requests. // // profileName is name of the CDN profile within the resource group // profileProperties is profile properties needed for creation // resourceGroupName is name of the resource group within the Azure // subscription -func (client ProfilesClient) Create(profileName string, profileProperties ProfileCreateParameters, resourceGroupName string) (result Profile, ae error) { - req, err := client.CreatePreparer(profileName, profileProperties, resourceGroupName) +func (client ProfilesClient) Create(profileName string, profileProperties ProfileCreateParameters, resourceGroupName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreatePreparer(profileName, profileProperties, resourceGroupName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "cdn/ProfilesClient", "Create", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "cdn.ProfilesClient", "Create", nil, "Failure preparing request") } resp, err := client.CreateSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "cdn/ProfilesClient", "Create", resp.StatusCode, "Failure sending request") + result.Response = resp + return result, autorest.NewErrorWithError(err, "cdn.ProfilesClient", "Create", resp, "Failure sending request") } result, err = client.CreateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "cdn/ProfilesClient", "Create", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "cdn.ProfilesClient", "Create", resp, "Failure responding to request") } return } // CreatePreparer prepares the Create request. -func (client ProfilesClient) CreatePreparer(profileName string, profileProperties ProfileCreateParameters, resourceGroupName string) (*http.Request, error) { +func (client ProfilesClient) CreatePreparer(profileName string, profileProperties ProfileCreateParameters, resourceGroupName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "profileName": url.QueryEscape(profileName), "resourceGroupName": url.QueryEscape(resourceGroupName), @@ -82,7 +85,7 @@ func (client ProfilesClient) CreatePreparer(profileName string, profilePropertie "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), @@ -95,49 +98,53 @@ func (client ProfilesClient) CreatePreparer(profileName string, profilePropertie // CreateSender sends the Create request. The method will close the // http.Response Body if it receives an error. func (client ProfilesClient) CreateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusCreated, http.StatusAccepted) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // CreateResponder handles the response to the Create request. The method always // closes the http.Response Body. -func (client ProfilesClient) CreateResponder(resp *http.Response) (result Profile, err error) { +func (client ProfilesClient) CreateResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + result.Response = resp return } -// DeleteIfExists sends the delete if exists request. +// DeleteIfExists sends the delete if exists request. This method may poll for +// completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. // // profileName is name of the CDN profile within the resource group // resourceGroupName is name of the resource group within the Azure // subscription -func (client ProfilesClient) DeleteIfExists(profileName string, resourceGroupName string) (result autorest.Response, ae error) { - req, err := client.DeleteIfExistsPreparer(profileName, resourceGroupName) +func (client ProfilesClient) DeleteIfExists(profileName string, resourceGroupName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeleteIfExistsPreparer(profileName, resourceGroupName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "cdn/ProfilesClient", "DeleteIfExists", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "cdn.ProfilesClient", "DeleteIfExists", nil, "Failure preparing request") } resp, err := client.DeleteIfExistsSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "cdn/ProfilesClient", "DeleteIfExists", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "cdn.ProfilesClient", "DeleteIfExists", resp, "Failure sending request") } result, err = client.DeleteIfExistsResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "cdn/ProfilesClient", "DeleteIfExists", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "cdn.ProfilesClient", "DeleteIfExists", resp, "Failure responding to request") } return } // DeleteIfExistsPreparer prepares the DeleteIfExists request. -func (client ProfilesClient) DeleteIfExistsPreparer(profileName string, resourceGroupName string) (*http.Request, error) { +func (client ProfilesClient) DeleteIfExistsPreparer(profileName string, resourceGroupName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "profileName": url.QueryEscape(profileName), "resourceGroupName": url.QueryEscape(resourceGroupName), @@ -148,7 +155,7 @@ func (client ProfilesClient) DeleteIfExistsPreparer(profileName string, resource "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), @@ -160,7 +167,9 @@ func (client ProfilesClient) DeleteIfExistsPreparer(profileName string, resource // DeleteIfExistsSender sends the DeleteIfExists request. The method will close the // http.Response Body if it receives an error. func (client ProfilesClient) DeleteIfExistsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted, http.StatusNoContent) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // DeleteIfExistsResponder handles the response to the DeleteIfExists request. The method always @@ -169,7 +178,7 @@ func (client ProfilesClient) DeleteIfExistsResponder(resp *http.Response) (resul err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return @@ -180,21 +189,21 @@ func (client ProfilesClient) DeleteIfExistsResponder(resp *http.Response) (resul // profileName is name of the CDN profile within the resource group // resourceGroupName is name of the resource group within the Azure // subscription -func (client ProfilesClient) GenerateSsoURI(profileName string, resourceGroupName string) (result SsoURI, ae error) { +func (client ProfilesClient) GenerateSsoURI(profileName string, resourceGroupName string) (result SsoURI, err error) { req, err := client.GenerateSsoURIPreparer(profileName, resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "cdn/ProfilesClient", "GenerateSsoURI", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "cdn.ProfilesClient", "GenerateSsoURI", nil, "Failure preparing request") } resp, err := client.GenerateSsoURISender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "cdn/ProfilesClient", "GenerateSsoURI", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "cdn.ProfilesClient", "GenerateSsoURI", resp, "Failure sending request") } result, err = client.GenerateSsoURIResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "cdn/ProfilesClient", "GenerateSsoURI", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "cdn.ProfilesClient", "GenerateSsoURI", resp, "Failure responding to request") } return @@ -224,7 +233,7 @@ func (client ProfilesClient) GenerateSsoURIPreparer(profileName string, resource // GenerateSsoURISender sends the GenerateSsoURI request. The method will close the // http.Response Body if it receives an error. func (client ProfilesClient) GenerateSsoURISender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GenerateSsoURIResponder handles the response to the GenerateSsoURI request. The method always @@ -233,7 +242,7 @@ func (client ProfilesClient) GenerateSsoURIResponder(resp *http.Response) (resul err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -245,21 +254,21 @@ func (client ProfilesClient) GenerateSsoURIResponder(resp *http.Response) (resul // profileName is name of the CDN profile within the resource group // resourceGroupName is name of the resource group within the Azure // subscription -func (client ProfilesClient) Get(profileName string, resourceGroupName string) (result Profile, ae error) { +func (client ProfilesClient) Get(profileName string, resourceGroupName string) (result Profile, err error) { req, err := client.GetPreparer(profileName, resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "cdn/ProfilesClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "cdn.ProfilesClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "cdn/ProfilesClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "cdn.ProfilesClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "cdn/ProfilesClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "cdn.ProfilesClient", "Get", resp, "Failure responding to request") } return @@ -289,7 +298,7 @@ func (client ProfilesClient) GetPreparer(profileName string, resourceGroupName s // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client ProfilesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -298,7 +307,7 @@ func (client ProfilesClient) GetResponder(resp *http.Response) (result Profile, err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -309,21 +318,21 @@ func (client ProfilesClient) GetResponder(resp *http.Response) (result Profile, // // resourceGroupName is name of the resource group within the Azure // subscription -func (client ProfilesClient) ListByResourceGroup(resourceGroupName string) (result ProfileListResult, ae error) { +func (client ProfilesClient) ListByResourceGroup(resourceGroupName string) (result ProfileListResult, err error) { req, err := client.ListByResourceGroupPreparer(resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "cdn/ProfilesClient", "ListByResourceGroup", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "cdn.ProfilesClient", "ListByResourceGroup", nil, "Failure preparing request") } resp, err := client.ListByResourceGroupSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "cdn/ProfilesClient", "ListByResourceGroup", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "cdn.ProfilesClient", "ListByResourceGroup", resp, "Failure sending request") } result, err = client.ListByResourceGroupResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "cdn/ProfilesClient", "ListByResourceGroup", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "cdn.ProfilesClient", "ListByResourceGroup", resp, "Failure responding to request") } return @@ -352,7 +361,7 @@ func (client ProfilesClient) ListByResourceGroupPreparer(resourceGroupName strin // ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the // http.Response Body if it receives an error. func (client ProfilesClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always @@ -361,7 +370,66 @@ func (client ProfilesClient) ListByResourceGroupResponder(resp *http.Response) ( err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListBySubscriptionID sends the list by subscription id request. +func (client ProfilesClient) ListBySubscriptionID() (result ProfileListResult, err error) { + req, err := client.ListBySubscriptionIDPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "cdn.ProfilesClient", "ListBySubscriptionID", nil, "Failure preparing request") + } + + resp, err := client.ListBySubscriptionIDSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "cdn.ProfilesClient", "ListBySubscriptionID", resp, "Failure sending request") + } + + result, err = client.ListBySubscriptionIDResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "cdn.ProfilesClient", "ListBySubscriptionID", resp, "Failure responding to request") + } + + return +} + +// ListBySubscriptionIDPreparer prepares the ListBySubscriptionID request. +func (client ProfilesClient) ListBySubscriptionIDPreparer() (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": url.QueryEscape(client.SubscriptionID), + } + + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPath("/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/profiles"), + autorest.WithPathParameters(pathParameters), + autorest.WithQueryParameters(queryParameters)) +} + +// ListBySubscriptionIDSender sends the ListBySubscriptionID request. The method will close the +// http.Response Body if it receives an error. +func (client ProfilesClient) ListBySubscriptionIDSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListBySubscriptionIDResponder handles the response to the ListBySubscriptionID request. The method always +// closes the http.Response Body. +func (client ProfilesClient) ListBySubscriptionIDResponder(resp *http.Response) (result ProfileListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -374,21 +442,21 @@ func (client ProfilesClient) ListByResourceGroupResponder(resp *http.Response) ( // profileProperties is profile properties needed for update // resourceGroupName is name of the resource group within the Azure // subscription -func (client ProfilesClient) Update(profileName string, profileProperties ProfileUpdateParameters, resourceGroupName string) (result Profile, ae error) { +func (client ProfilesClient) Update(profileName string, profileProperties ProfileUpdateParameters, resourceGroupName string) (result Profile, err error) { req, err := client.UpdatePreparer(profileName, profileProperties, resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "cdn/ProfilesClient", "Update", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "cdn.ProfilesClient", "Update", nil, "Failure preparing request") } resp, err := client.UpdateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "cdn/ProfilesClient", "Update", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "cdn.ProfilesClient", "Update", resp, "Failure sending request") } result, err = client.UpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "cdn/ProfilesClient", "Update", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "cdn.ProfilesClient", "Update", resp, "Failure responding to request") } return @@ -419,7 +487,7 @@ func (client ProfilesClient) UpdatePreparer(profileName string, profilePropertie // UpdateSender sends the Update request. The method will close the // http.Response Body if it receives an error. func (client ProfilesClient) UpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted) + return autorest.SendWithSender(client, req) } // UpdateResponder handles the response to the Update request. The method always @@ -428,7 +496,7 @@ func (client ProfilesClient) UpdateResponder(resp *http.Response) (result Profil err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/version.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/version.go index 2fafc41e53e2..874d7defb97f 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/version.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/cdn/version.go @@ -14,7 +14,7 @@ package cdn // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -23,13 +23,13 @@ import ( ) const ( - major = "0" - minor = "4" - patch = "0" + major = "2" + minor = "1" + patch = "1" // Always begin a "tag" with a dash (as per http://semver.org) tag = "-beta" semVerFormat = "%s.%s.%s%s" - userAgentFormat = "Azure-SDK-for-Go/%s;Package arm/%s;API %s" + userAgentFormat = "Azure-SDK-for-Go/%s arm-%s/%s" ) // UserAgent returns the UserAgent string to use when sending http.Requests. diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/availabilitysets.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/availabilitysets.go index 4e740ff40fb5..d2eb1d39690a 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/availabilitysets.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/availabilitysets.go @@ -14,12 +14,13 @@ package compute // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -46,21 +47,21 @@ func NewAvailabilitySetsClientWithBaseURI(baseURI string, subscriptionID string) // resourceGroupName is the name of the resource group. name is parameters // supplied to the Create Availability Set operation. parameters is // parameters supplied to the Create Availability Set operation. -func (client AvailabilitySetsClient) CreateOrUpdate(resourceGroupName string, name string, parameters AvailabilitySet) (result AvailabilitySet, ae error) { +func (client AvailabilitySetsClient) CreateOrUpdate(resourceGroupName string, name string, parameters AvailabilitySet) (result AvailabilitySet, err error) { req, err := client.CreateOrUpdatePreparer(resourceGroupName, name, parameters) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/AvailabilitySetsClient", "CreateOrUpdate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "CreateOrUpdate", nil, "Failure preparing request") } resp, err := client.CreateOrUpdateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/AvailabilitySetsClient", "CreateOrUpdate", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "CreateOrUpdate", resp, "Failure sending request") } result, err = client.CreateOrUpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/AvailabilitySetsClient", "CreateOrUpdate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "CreateOrUpdate", resp, "Failure responding to request") } return @@ -91,7 +92,7 @@ func (client AvailabilitySetsClient) CreateOrUpdatePreparer(resourceGroupName st // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client AvailabilitySetsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always @@ -100,7 +101,7 @@ func (client AvailabilitySetsClient) CreateOrUpdateResponder(resp *http.Response err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -111,21 +112,21 @@ func (client AvailabilitySetsClient) CreateOrUpdateResponder(resp *http.Response // // resourceGroupName is the name of the resource group. availabilitySetName is // the name of the availability set. -func (client AvailabilitySetsClient) Delete(resourceGroupName string, availabilitySetName string) (result autorest.Response, ae error) { +func (client AvailabilitySetsClient) Delete(resourceGroupName string, availabilitySetName string) (result autorest.Response, err error) { req, err := client.DeletePreparer(resourceGroupName, availabilitySetName) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/AvailabilitySetsClient", "Delete", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Delete", nil, "Failure preparing request") } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "compute/AvailabilitySetsClient", "Delete", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Delete", resp, "Failure sending request") } result, err = client.DeleteResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/AvailabilitySetsClient", "Delete", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Delete", resp, "Failure responding to request") } return @@ -155,7 +156,7 @@ func (client AvailabilitySetsClient) DeletePreparer(resourceGroupName string, av // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client AvailabilitySetsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusNoContent, http.StatusOK) + return autorest.SendWithSender(client, req) } // DeleteResponder handles the response to the Delete request. The method always @@ -164,7 +165,7 @@ func (client AvailabilitySetsClient) DeleteResponder(resp *http.Response) (resul err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusOK), autorest.ByClosing()) result.Response = resp return @@ -174,21 +175,21 @@ func (client AvailabilitySetsClient) DeleteResponder(resp *http.Response) (resul // // resourceGroupName is the name of the resource group. availabilitySetName is // the name of the availability set. -func (client AvailabilitySetsClient) Get(resourceGroupName string, availabilitySetName string) (result AvailabilitySet, ae error) { +func (client AvailabilitySetsClient) Get(resourceGroupName string, availabilitySetName string) (result AvailabilitySet, err error) { req, err := client.GetPreparer(resourceGroupName, availabilitySetName) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/AvailabilitySetsClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/AvailabilitySetsClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/AvailabilitySetsClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Get", resp, "Failure responding to request") } return @@ -218,7 +219,7 @@ func (client AvailabilitySetsClient) GetPreparer(resourceGroupName string, avail // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client AvailabilitySetsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -227,7 +228,7 @@ func (client AvailabilitySetsClient) GetResponder(resp *http.Response) (result A err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -237,21 +238,21 @@ func (client AvailabilitySetsClient) GetResponder(resp *http.Response) (result A // List the operation to list the availability sets. // // resourceGroupName is the name of the resource group. -func (client AvailabilitySetsClient) List(resourceGroupName string) (result AvailabilitySetListResult, ae error) { +func (client AvailabilitySetsClient) List(resourceGroupName string) (result AvailabilitySetListResult, err error) { req, err := client.ListPreparer(resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/AvailabilitySetsClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/AvailabilitySetsClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/AvailabilitySetsClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "List", resp, "Failure responding to request") } return @@ -280,7 +281,7 @@ func (client AvailabilitySetsClient) ListPreparer(resourceGroupName string) (*ht // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client AvailabilitySetsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -289,7 +290,7 @@ func (client AvailabilitySetsClient) ListResponder(resp *http.Response) (result err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -297,10 +298,10 @@ func (client AvailabilitySetsClient) ListResponder(resp *http.Response) (result } // ListNextResults retrieves the next set of results, if any. -func (client AvailabilitySetsClient) ListNextResults(lastResults AvailabilitySetListResult) (result AvailabilitySetListResult, ae error) { +func (client AvailabilitySetsClient) ListNextResults(lastResults AvailabilitySetListResult) (result AvailabilitySetListResult, err error) { req, err := lastResults.AvailabilitySetListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "compute/AvailabilitySetsClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -309,12 +310,12 @@ func (client AvailabilitySetsClient) ListNextResults(lastResults AvailabilitySet resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/AvailabilitySetsClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/AvailabilitySetsClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "List", resp, "Failure responding to next results request request") } return @@ -325,21 +326,21 @@ func (client AvailabilitySetsClient) ListNextResults(lastResults AvailabilitySet // // resourceGroupName is the name of the resource group. availabilitySetName is // the name of the availability set. -func (client AvailabilitySetsClient) ListAvailableSizes(resourceGroupName string, availabilitySetName string) (result VirtualMachineSizeListResult, ae error) { +func (client AvailabilitySetsClient) ListAvailableSizes(resourceGroupName string, availabilitySetName string) (result VirtualMachineSizeListResult, err error) { req, err := client.ListAvailableSizesPreparer(resourceGroupName, availabilitySetName) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/AvailabilitySetsClient", "ListAvailableSizes", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "ListAvailableSizes", nil, "Failure preparing request") } resp, err := client.ListAvailableSizesSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/AvailabilitySetsClient", "ListAvailableSizes", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "ListAvailableSizes", resp, "Failure sending request") } result, err = client.ListAvailableSizesResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/AvailabilitySetsClient", "ListAvailableSizes", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "ListAvailableSizes", resp, "Failure responding to request") } return @@ -369,7 +370,7 @@ func (client AvailabilitySetsClient) ListAvailableSizesPreparer(resourceGroupNam // ListAvailableSizesSender sends the ListAvailableSizes request. The method will close the // http.Response Body if it receives an error. func (client AvailabilitySetsClient) ListAvailableSizesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListAvailableSizesResponder handles the response to the ListAvailableSizes request. The method always @@ -378,7 +379,7 @@ func (client AvailabilitySetsClient) ListAvailableSizesResponder(resp *http.Resp err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -386,10 +387,10 @@ func (client AvailabilitySetsClient) ListAvailableSizesResponder(resp *http.Resp } // ListAvailableSizesNextResults retrieves the next set of results, if any. -func (client AvailabilitySetsClient) ListAvailableSizesNextResults(lastResults VirtualMachineSizeListResult) (result VirtualMachineSizeListResult, ae error) { +func (client AvailabilitySetsClient) ListAvailableSizesNextResults(lastResults VirtualMachineSizeListResult) (result VirtualMachineSizeListResult, err error) { req, err := lastResults.VirtualMachineSizeListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "compute/AvailabilitySetsClient", "ListAvailableSizes", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "ListAvailableSizes", nil, "Failure preparing next results request request") } if req == nil { return @@ -398,12 +399,12 @@ func (client AvailabilitySetsClient) ListAvailableSizesNextResults(lastResults V resp, err := client.ListAvailableSizesSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/AvailabilitySetsClient", "ListAvailableSizes", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "ListAvailableSizes", resp, "Failure sending next results request request") } result, err = client.ListAvailableSizesResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/AvailabilitySetsClient", "ListAvailableSizes", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "ListAvailableSizes", resp, "Failure responding to next results request request") } return diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/client.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/client.go index 537fd11968a9..5ed123ca27d5 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/client.go @@ -1,3 +1,7 @@ +// Package compute implements the Azure ARM Compute service API version +// 2015-06-15. +// +// The Compute Management Client. package compute // Copyright (c) Microsoft and contributors. All rights reserved. @@ -14,12 +18,12 @@ package compute // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" ) const ( @@ -30,7 +34,7 @@ const ( DefaultBaseURI = "https://management.azure.com" ) -// ManagementClient is the the Compute Management Client. +// ManagementClient is the base client for Compute. type ManagementClient struct { autorest.Client BaseURI string diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/models.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/models.go index 2936a2bc5c60..0de6024041a5 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/models.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/models.go @@ -14,14 +14,14 @@ package compute // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/date" - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/to" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/date" + "github.com/Azure/go-autorest/autorest/to" "net/http" ) @@ -394,8 +394,8 @@ func (client AvailabilitySetListResult) AvailabilitySetListResultPreparer() (*ht // AvailabilitySetProperties is the instance view of a resource. type AvailabilitySetProperties struct { - PlatformUpdateDomainCount *int `json:"platformUpdateDomainCount,omitempty"` - PlatformFaultDomainCount *int `json:"platformFaultDomainCount,omitempty"` + PlatformUpdateDomainCount *int32 `json:"platformUpdateDomainCount,omitempty"` + PlatformFaultDomainCount *int32 `json:"platformFaultDomainCount,omitempty"` VirtualMachines *[]SubResource `json:"virtualMachines,omitempty"` Statuses *[]InstanceViewStatus `json:"statuses,omitempty"` } @@ -415,18 +415,18 @@ type BootDiagnosticsInstanceView struct { // DataDisk is describes a data disk. type DataDisk struct { - Lun *int `json:"lun,omitempty"` + Lun *int32 `json:"lun,omitempty"` Name *string `json:"name,omitempty"` Vhd *VirtualHardDisk `json:"vhd,omitempty"` Image *VirtualHardDisk `json:"image,omitempty"` Caching CachingTypes `json:"caching,omitempty"` CreateOption DiskCreateOptionTypes `json:"createOption,omitempty"` - DiskSizeGB *int `json:"diskSizeGB,omitempty"` + DiskSizeGB *int32 `json:"diskSizeGB,omitempty"` } // DataDiskImage is contains the data disk images information. type DataDiskImage struct { - Lun *int `json:"lun,omitempty"` + Lun *int32 `json:"lun,omitempty"` } // DeleteOperationResult is the compute long running operation response. @@ -520,6 +520,12 @@ func (client ListUsagesResult) ListUsagesResultPreparer() (*http.Request, error) autorest.WithBaseURL(to.String(client.NextLink))) } +// ListVirtualMachineImageResource is +type ListVirtualMachineImageResource struct { + autorest.Response `json:"-"` + Value *[]VirtualMachineImageResource `json:"value,omitempty"` +} + // LongRunningOperationProperties is compute-specific operation properties, // including output type LongRunningOperationProperties struct { @@ -563,7 +569,7 @@ type OSDisk struct { Image *VirtualHardDisk `json:"image,omitempty"` Caching CachingTypes `json:"caching,omitempty"` CreateOption DiskCreateOptionTypes `json:"createOption,omitempty"` - DiskSizeGB *int `json:"diskSizeGB,omitempty"` + DiskSizeGB *int32 `json:"diskSizeGB,omitempty"` } // OSDiskImage is contains the os disk image information. @@ -611,7 +617,7 @@ type Resource struct { type Sku struct { Name *string `json:"name,omitempty"` Tier *string `json:"tier,omitempty"` - Capacity *int32 `json:"capacity,omitempty"` + Capacity *int64 `json:"capacity,omitempty"` } // SSHConfiguration is sSH configuration for Linux based VMs running on Azure @@ -646,8 +652,8 @@ type UpgradePolicy struct { // Usage is describes Compute Resource Usage. type Usage struct { Unit UsageUnit `json:"unit,omitempty"` - CurrentValue *int `json:"currentValue,omitempty"` - Limit *int32 `json:"limit,omitempty"` + CurrentValue *int32 `json:"currentValue,omitempty"` + Limit *int64 `json:"limit,omitempty"` Name *UsageName `json:"name,omitempty"` } @@ -805,16 +811,10 @@ type VirtualMachineImageResource struct { Tags *map[string]*string `json:"tags,omitempty"` } -// VirtualMachineImageResourceList is -type VirtualMachineImageResourceList struct { - autorest.Response `json:"-"` - Value *VirtualMachineImageResource `json:"value,omitempty"` -} - // VirtualMachineInstanceView is the instance view of a virtual machine. type VirtualMachineInstanceView struct { - PlatformUpdateDomain *int `json:"platformUpdateDomain,omitempty"` - PlatformFaultDomain *int `json:"platformFaultDomain,omitempty"` + PlatformUpdateDomain *int32 `json:"platformUpdateDomain,omitempty"` + PlatformFaultDomain *int32 `json:"platformFaultDomain,omitempty"` RdpThumbPrint *string `json:"rdpThumbPrint,omitempty"` VMAgent *VirtualMachineAgentInstanceView `json:"vmAgent,omitempty"` Disks *[]DiskInstanceView `json:"disks,omitempty"` @@ -1044,9 +1044,9 @@ type VirtualMachineScaleSetSku struct { // VirtualMachineScaleSetSkuCapacity is describes scaling information of a sku. type VirtualMachineScaleSetSkuCapacity struct { - Minimum *int32 `json:"minimum,omitempty"` - Maximum *int32 `json:"maximum,omitempty"` - DefaultCapacity *int32 `json:"defaultCapacity,omitempty"` + Minimum *int64 `json:"minimum,omitempty"` + Maximum *int64 `json:"maximum,omitempty"` + DefaultCapacity *int64 `json:"defaultCapacity,omitempty"` ScaleType VirtualMachineScaleSetSkuScaleType `json:"scaleType,omitempty"` } @@ -1096,8 +1096,8 @@ type VirtualMachineScaleSetVMInstanceRequiredIDs struct { // machine scale set VM. type VirtualMachineScaleSetVMInstanceView struct { autorest.Response `json:"-"` - PlatformUpdateDomain *int `json:"platformUpdateDomain,omitempty"` - PlatformFaultDomain *int `json:"platformFaultDomain,omitempty"` + PlatformUpdateDomain *int32 `json:"platformUpdateDomain,omitempty"` + PlatformFaultDomain *int32 `json:"platformFaultDomain,omitempty"` RdpThumbPrint *string `json:"rdpThumbPrint,omitempty"` VMAgent *VirtualMachineAgentInstanceView `json:"vmAgent,omitempty"` Disks *[]DiskInstanceView `json:"disks,omitempty"` @@ -1152,11 +1152,11 @@ type VirtualMachineScaleSetVMProperties struct { // VirtualMachineSize is describes the properties of a VM size. type VirtualMachineSize struct { Name *string `json:"name,omitempty"` - NumberOfCores *int `json:"numberOfCores,omitempty"` - OsDiskSizeInMB *int `json:"osDiskSizeInMB,omitempty"` - ResourceDiskSizeInMB *int `json:"resourceDiskSizeInMB,omitempty"` - MemoryInMB *int `json:"memoryInMB,omitempty"` - MaxDataDiskCount *int `json:"maxDataDiskCount,omitempty"` + NumberOfCores *int32 `json:"numberOfCores,omitempty"` + OsDiskSizeInMB *int32 `json:"osDiskSizeInMB,omitempty"` + ResourceDiskSizeInMB *int32 `json:"resourceDiskSizeInMB,omitempty"` + MemoryInMB *int32 `json:"memoryInMB,omitempty"` + MaxDataDiskCount *int32 `json:"maxDataDiskCount,omitempty"` } // VirtualMachineSizeListResult is the List Virtual Machine operation response. @@ -1182,7 +1182,7 @@ func (client VirtualMachineSizeListResult) VirtualMachineSizeListResultPreparer( // machine scale set instance view status summary. type VirtualMachineStatusCodeCount struct { Code *string `json:"code,omitempty"` - Count *int `json:"count,omitempty"` + Count *int32 `json:"count,omitempty"` } // WindowsConfiguration is describes Windows Configuration of the OS Profile. diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/usageoperations.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/usageoperations.go index 93ff10c33b7e..11a6076889ec 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/usageoperations.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/usageoperations.go @@ -14,12 +14,13 @@ package compute // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -44,21 +45,21 @@ func NewUsageOperationsClientWithBaseURI(baseURI string, subscriptionID string) // List lists compute usages for a subscription. // // location is the location upon which resource usage is queried. -func (client UsageOperationsClient) List(location string) (result ListUsagesResult, ae error) { +func (client UsageOperationsClient) List(location string) (result ListUsagesResult, err error) { req, err := client.ListPreparer(location) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/UsageOperationsClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.UsageOperationsClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/UsageOperationsClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.UsageOperationsClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/UsageOperationsClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.UsageOperationsClient", "List", resp, "Failure responding to request") } return @@ -87,7 +88,7 @@ func (client UsageOperationsClient) ListPreparer(location string) (*http.Request // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client UsageOperationsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -96,7 +97,7 @@ func (client UsageOperationsClient) ListResponder(resp *http.Response) (result L err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -104,10 +105,10 @@ func (client UsageOperationsClient) ListResponder(resp *http.Response) (result L } // ListNextResults retrieves the next set of results, if any. -func (client UsageOperationsClient) ListNextResults(lastResults ListUsagesResult) (result ListUsagesResult, ae error) { +func (client UsageOperationsClient) ListNextResults(lastResults ListUsagesResult) (result ListUsagesResult, err error) { req, err := lastResults.ListUsagesResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "compute/UsageOperationsClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "compute.UsageOperationsClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -116,12 +117,12 @@ func (client UsageOperationsClient) ListNextResults(lastResults ListUsagesResult resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/UsageOperationsClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "compute.UsageOperationsClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/UsageOperationsClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "compute.UsageOperationsClient", "List", resp, "Failure responding to next results request request") } return diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/version.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/version.go index 93d1fde86f34..eef4c7e7aee7 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/version.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/version.go @@ -14,7 +14,7 @@ package compute // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -23,13 +23,13 @@ import ( ) const ( - major = "0" - minor = "4" - patch = "0" + major = "2" + minor = "1" + patch = "1" // Always begin a "tag" with a dash (as per http://semver.org) tag = "-beta" semVerFormat = "%s.%s.%s%s" - userAgentFormat = "Azure-SDK-for-Go/%s;Package arm/%s;API %s" + userAgentFormat = "Azure-SDK-for-Go/%s arm-%s/%s" ) // UserAgent returns the UserAgent string to use when sending http.Requests. diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachineextensionimages.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachineextensionimages.go index 97355ee7c2e7..cf0a5acf80c5 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachineextensionimages.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachineextensionimages.go @@ -14,12 +14,13 @@ package compute // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -43,21 +44,21 @@ func NewVirtualMachineExtensionImagesClientWithBaseURI(baseURI string, subscript // Get gets a virtual machine extension image. // -func (client VirtualMachineExtensionImagesClient) Get(location string, publisherName string, typeParameter string, version string) (result VirtualMachineExtensionImage, ae error) { +func (client VirtualMachineExtensionImagesClient) Get(location string, publisherName string, typeParameter string, version string) (result VirtualMachineExtensionImage, err error) { req, err := client.GetPreparer(location, publisherName, typeParameter, version) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineExtensionImagesClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineExtensionImagesClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineExtensionImagesClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "Get", resp, "Failure responding to request") } return @@ -89,7 +90,7 @@ func (client VirtualMachineExtensionImagesClient) GetPreparer(location string, p // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineExtensionImagesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -98,7 +99,7 @@ func (client VirtualMachineExtensionImagesClient) GetResponder(resp *http.Respon err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -107,21 +108,21 @@ func (client VirtualMachineExtensionImagesClient) GetResponder(resp *http.Respon // ListTypes gets a list of virtual machine extension image types. // -func (client VirtualMachineExtensionImagesClient) ListTypes(location string, publisherName string) (result VirtualMachineImageResourceList, ae error) { +func (client VirtualMachineExtensionImagesClient) ListTypes(location string, publisherName string) (result ListVirtualMachineImageResource, err error) { req, err := client.ListTypesPreparer(location, publisherName) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineExtensionImagesClient", "ListTypes", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListTypes", nil, "Failure preparing request") } resp, err := client.ListTypesSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineExtensionImagesClient", "ListTypes", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListTypes", resp, "Failure sending request") } result, err = client.ListTypesResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineExtensionImagesClient", "ListTypes", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListTypes", resp, "Failure responding to request") } return @@ -151,16 +152,16 @@ func (client VirtualMachineExtensionImagesClient) ListTypesPreparer(location str // ListTypesSender sends the ListTypes request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineExtensionImagesClient) ListTypesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListTypesResponder handles the response to the ListTypes request. The method always // closes the http.Response Body. -func (client VirtualMachineExtensionImagesClient) ListTypesResponder(resp *http.Response) (result VirtualMachineImageResourceList, err error) { +func (client VirtualMachineExtensionImagesClient) ListTypesResponder(resp *http.Response) (result ListVirtualMachineImageResource, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result.Value), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -170,28 +171,28 @@ func (client VirtualMachineExtensionImagesClient) ListTypesResponder(resp *http. // ListVersions gets a list of virtual machine extension image versions. // // filter is the filter to apply on the operation. -func (client VirtualMachineExtensionImagesClient) ListVersions(location string, publisherName string, typeParameter string, filter string, top *int, orderBy string) (result VirtualMachineImageResourceList, ae error) { +func (client VirtualMachineExtensionImagesClient) ListVersions(location string, publisherName string, typeParameter string, filter string, top *int32, orderBy string) (result ListVirtualMachineImageResource, err error) { req, err := client.ListVersionsPreparer(location, publisherName, typeParameter, filter, top, orderBy) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineExtensionImagesClient", "ListVersions", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListVersions", nil, "Failure preparing request") } resp, err := client.ListVersionsSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineExtensionImagesClient", "ListVersions", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListVersions", resp, "Failure sending request") } result, err = client.ListVersionsResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineExtensionImagesClient", "ListVersions", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListVersions", resp, "Failure responding to request") } return } // ListVersionsPreparer prepares the ListVersions request. -func (client VirtualMachineExtensionImagesClient) ListVersionsPreparer(location string, publisherName string, typeParameter string, filter string, top *int, orderBy string) (*http.Request, error) { +func (client VirtualMachineExtensionImagesClient) ListVersionsPreparer(location string, publisherName string, typeParameter string, filter string, top *int32, orderBy string) (*http.Request, error) { pathParameters := map[string]interface{}{ "location": url.QueryEscape(location), "publisherName": url.QueryEscape(publisherName), @@ -224,16 +225,16 @@ func (client VirtualMachineExtensionImagesClient) ListVersionsPreparer(location // ListVersionsSender sends the ListVersions request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineExtensionImagesClient) ListVersionsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListVersionsResponder handles the response to the ListVersions request. The method always // closes the http.Response Body. -func (client VirtualMachineExtensionImagesClient) ListVersionsResponder(resp *http.Response) (result VirtualMachineImageResourceList, err error) { +func (client VirtualMachineExtensionImagesClient) ListVersionsResponder(resp *http.Response) (result ListVirtualMachineImageResource, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result.Value), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachineextensions.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachineextensions.go index 97255c5e5806..af937c6f4e7c 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachineextensions.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachineextensions.go @@ -14,12 +14,13 @@ package compute // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -41,35 +42,38 @@ func NewVirtualMachineExtensionsClientWithBaseURI(baseURI string, subscriptionID return VirtualMachineExtensionsClient{NewWithBaseURI(baseURI, subscriptionID)} } -// CreateOrUpdate the operation to create or update the extension. +// CreateOrUpdate the operation to create or update the extension. This method +// may poll for completion. Polling can be canceled by passing the cancel +// channel argument. The channel will be used to cancel polling and any +// outstanding HTTP requests. // // resourceGroupName is the name of the resource group. vmName is the name of // the virtual machine where the extension should be create or updated. // vmExtensionName is the name of the virtual machine extension. // extensionParameters is parameters supplied to the Create Virtual Machine // Extension operation. -func (client VirtualMachineExtensionsClient) CreateOrUpdate(resourceGroupName string, vmName string, vmExtensionName string, extensionParameters VirtualMachineExtension) (result VirtualMachineExtension, ae error) { - req, err := client.CreateOrUpdatePreparer(resourceGroupName, vmName, vmExtensionName, extensionParameters) +func (client VirtualMachineExtensionsClient) CreateOrUpdate(resourceGroupName string, vmName string, vmExtensionName string, extensionParameters VirtualMachineExtension, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, vmName, vmExtensionName, extensionParameters, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineExtensionsClient", "CreateOrUpdate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "CreateOrUpdate", nil, "Failure preparing request") } resp, err := client.CreateOrUpdateSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineExtensionsClient", "CreateOrUpdate", resp.StatusCode, "Failure sending request") + result.Response = resp + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "CreateOrUpdate", resp, "Failure sending request") } result, err = client.CreateOrUpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineExtensionsClient", "CreateOrUpdate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "CreateOrUpdate", resp, "Failure responding to request") } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualMachineExtensionsClient) CreateOrUpdatePreparer(resourceGroupName string, vmName string, vmExtensionName string, extensionParameters VirtualMachineExtension) (*http.Request, error) { +func (client VirtualMachineExtensionsClient) CreateOrUpdatePreparer(resourceGroupName string, vmName string, vmExtensionName string, extensionParameters VirtualMachineExtension, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "subscriptionId": url.QueryEscape(client.SubscriptionID), @@ -81,7 +85,7 @@ func (client VirtualMachineExtensionsClient) CreateOrUpdatePreparer(resourceGrou "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), @@ -94,49 +98,53 @@ func (client VirtualMachineExtensionsClient) CreateOrUpdatePreparer(resourceGrou // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineExtensionsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusCreated, http.StatusOK) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client VirtualMachineExtensionsClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualMachineExtension, err error) { +func (client VirtualMachineExtensionsClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), - autorest.ByUnmarshallingJSON(&result), + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + result.Response = resp return } -// Delete the operation to delete the extension. +// Delete the operation to delete the extension. This method may poll for +// completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. // // resourceGroupName is the name of the resource group. vmName is the name of // the virtual machine where the extension should be deleted. vmExtensionName // is the name of the virtual machine extension. -func (client VirtualMachineExtensionsClient) Delete(resourceGroupName string, vmName string, vmExtensionName string) (result autorest.Response, ae error) { - req, err := client.DeletePreparer(resourceGroupName, vmName, vmExtensionName) +func (client VirtualMachineExtensionsClient) Delete(resourceGroupName string, vmName string, vmExtensionName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, vmName, vmExtensionName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineExtensionsClient", "Delete", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "Delete", nil, "Failure preparing request") } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineExtensionsClient", "Delete", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "Delete", resp, "Failure sending request") } result, err = client.DeleteResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineExtensionsClient", "Delete", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "Delete", resp, "Failure responding to request") } return } // DeletePreparer prepares the Delete request. -func (client VirtualMachineExtensionsClient) DeletePreparer(resourceGroupName string, vmName string, vmExtensionName string) (*http.Request, error) { +func (client VirtualMachineExtensionsClient) DeletePreparer(resourceGroupName string, vmName string, vmExtensionName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "subscriptionId": url.QueryEscape(client.SubscriptionID), @@ -148,7 +156,7 @@ func (client VirtualMachineExtensionsClient) DeletePreparer(resourceGroupName st "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), @@ -160,7 +168,9 @@ func (client VirtualMachineExtensionsClient) DeletePreparer(resourceGroupName st // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineExtensionsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusAccepted, http.StatusNoContent, http.StatusOK) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // DeleteResponder handles the response to the Delete request. The method always @@ -169,7 +179,7 @@ func (client VirtualMachineExtensionsClient) DeleteResponder(resp *http.Response err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusNoContent, http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusNoContent, http.StatusOK), autorest.ByClosing()) result.Response = resp return @@ -181,21 +191,21 @@ func (client VirtualMachineExtensionsClient) DeleteResponder(resp *http.Response // the virtual machine containing the extension. vmExtensionName is the name // of the virtual machine extension. expand is the expand expression to apply // on the operation. -func (client VirtualMachineExtensionsClient) Get(resourceGroupName string, vmName string, vmExtensionName string, expand string) (result VirtualMachineExtension, ae error) { +func (client VirtualMachineExtensionsClient) Get(resourceGroupName string, vmName string, vmExtensionName string, expand string) (result VirtualMachineExtension, err error) { req, err := client.GetPreparer(resourceGroupName, vmName, vmExtensionName, expand) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineExtensionsClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineExtensionsClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineExtensionsClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "Get", resp, "Failure responding to request") } return @@ -229,7 +239,7 @@ func (client VirtualMachineExtensionsClient) GetPreparer(resourceGroupName strin // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineExtensionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -238,7 +248,7 @@ func (client VirtualMachineExtensionsClient) GetResponder(resp *http.Response) ( err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachineimages.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachineimages.go index 0b3c23ce5093..487332eb3c4a 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachineimages.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachineimages.go @@ -14,12 +14,13 @@ package compute // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -43,21 +44,21 @@ func NewVirtualMachineImagesClientWithBaseURI(baseURI string, subscriptionID str // Get gets a virtual machine image. // -func (client VirtualMachineImagesClient) Get(location string, publisherName string, offer string, skus string, version string) (result VirtualMachineImage, ae error) { +func (client VirtualMachineImagesClient) Get(location string, publisherName string, offer string, skus string, version string) (result VirtualMachineImage, err error) { req, err := client.GetPreparer(location, publisherName, offer, skus, version) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineImagesClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineImagesClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineImagesClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "Get", resp, "Failure responding to request") } return @@ -90,7 +91,7 @@ func (client VirtualMachineImagesClient) GetPreparer(location string, publisherN // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineImagesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -99,7 +100,7 @@ func (client VirtualMachineImagesClient) GetResponder(resp *http.Response) (resu err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -109,28 +110,28 @@ func (client VirtualMachineImagesClient) GetResponder(resp *http.Response) (resu // List gets a list of virtual machine images. // // filter is the filter to apply on the operation. -func (client VirtualMachineImagesClient) List(location string, publisherName string, offer string, skus string, filter string, top *int, orderby string) (result VirtualMachineImageResourceList, ae error) { +func (client VirtualMachineImagesClient) List(location string, publisherName string, offer string, skus string, filter string, top *int32, orderby string) (result ListVirtualMachineImageResource, err error) { req, err := client.ListPreparer(location, publisherName, offer, skus, filter, top, orderby) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineImagesClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineImagesClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineImagesClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "List", resp, "Failure responding to request") } return } // ListPreparer prepares the List request. -func (client VirtualMachineImagesClient) ListPreparer(location string, publisherName string, offer string, skus string, filter string, top *int, orderby string) (*http.Request, error) { +func (client VirtualMachineImagesClient) ListPreparer(location string, publisherName string, offer string, skus string, filter string, top *int32, orderby string) (*http.Request, error) { pathParameters := map[string]interface{}{ "location": url.QueryEscape(location), "offer": url.QueryEscape(offer), @@ -164,16 +165,16 @@ func (client VirtualMachineImagesClient) ListPreparer(location string, publisher // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineImagesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always // closes the http.Response Body. -func (client VirtualMachineImagesClient) ListResponder(resp *http.Response) (result VirtualMachineImageResourceList, err error) { +func (client VirtualMachineImagesClient) ListResponder(resp *http.Response) (result ListVirtualMachineImageResource, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result.Value), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -182,21 +183,21 @@ func (client VirtualMachineImagesClient) ListResponder(resp *http.Response) (res // ListOffers gets a list of virtual machine image offers. // -func (client VirtualMachineImagesClient) ListOffers(location string, publisherName string) (result VirtualMachineImageResourceList, ae error) { +func (client VirtualMachineImagesClient) ListOffers(location string, publisherName string) (result ListVirtualMachineImageResource, err error) { req, err := client.ListOffersPreparer(location, publisherName) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineImagesClient", "ListOffers", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListOffers", nil, "Failure preparing request") } resp, err := client.ListOffersSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineImagesClient", "ListOffers", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListOffers", resp, "Failure sending request") } result, err = client.ListOffersResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineImagesClient", "ListOffers", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListOffers", resp, "Failure responding to request") } return @@ -226,16 +227,16 @@ func (client VirtualMachineImagesClient) ListOffersPreparer(location string, pub // ListOffersSender sends the ListOffers request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineImagesClient) ListOffersSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListOffersResponder handles the response to the ListOffers request. The method always // closes the http.Response Body. -func (client VirtualMachineImagesClient) ListOffersResponder(resp *http.Response) (result VirtualMachineImageResourceList, err error) { +func (client VirtualMachineImagesClient) ListOffersResponder(resp *http.Response) (result ListVirtualMachineImageResource, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result.Value), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -244,21 +245,21 @@ func (client VirtualMachineImagesClient) ListOffersResponder(resp *http.Response // ListPublishers gets a list of virtual machine image publishers. // -func (client VirtualMachineImagesClient) ListPublishers(location string) (result VirtualMachineImageResourceList, ae error) { +func (client VirtualMachineImagesClient) ListPublishers(location string) (result ListVirtualMachineImageResource, err error) { req, err := client.ListPublishersPreparer(location) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineImagesClient", "ListPublishers", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListPublishers", nil, "Failure preparing request") } resp, err := client.ListPublishersSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineImagesClient", "ListPublishers", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListPublishers", resp, "Failure sending request") } result, err = client.ListPublishersResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineImagesClient", "ListPublishers", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListPublishers", resp, "Failure responding to request") } return @@ -287,16 +288,16 @@ func (client VirtualMachineImagesClient) ListPublishersPreparer(location string) // ListPublishersSender sends the ListPublishers request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineImagesClient) ListPublishersSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListPublishersResponder handles the response to the ListPublishers request. The method always // closes the http.Response Body. -func (client VirtualMachineImagesClient) ListPublishersResponder(resp *http.Response) (result VirtualMachineImageResourceList, err error) { +func (client VirtualMachineImagesClient) ListPublishersResponder(resp *http.Response) (result ListVirtualMachineImageResource, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result.Value), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -305,21 +306,21 @@ func (client VirtualMachineImagesClient) ListPublishersResponder(resp *http.Resp // ListSkus gets a list of virtual machine image skus. // -func (client VirtualMachineImagesClient) ListSkus(location string, publisherName string, offer string) (result VirtualMachineImageResourceList, ae error) { +func (client VirtualMachineImagesClient) ListSkus(location string, publisherName string, offer string) (result ListVirtualMachineImageResource, err error) { req, err := client.ListSkusPreparer(location, publisherName, offer) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineImagesClient", "ListSkus", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListSkus", nil, "Failure preparing request") } resp, err := client.ListSkusSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineImagesClient", "ListSkus", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListSkus", resp, "Failure sending request") } result, err = client.ListSkusResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineImagesClient", "ListSkus", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListSkus", resp, "Failure responding to request") } return @@ -350,16 +351,16 @@ func (client VirtualMachineImagesClient) ListSkusPreparer(location string, publi // ListSkusSender sends the ListSkus request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineImagesClient) ListSkusSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListSkusResponder handles the response to the ListSkus request. The method always // closes the http.Response Body. -func (client VirtualMachineImagesClient) ListSkusResponder(resp *http.Response) (result VirtualMachineImageResourceList, err error) { +func (client VirtualMachineImagesClient) ListSkusResponder(resp *http.Response) (result ListVirtualMachineImageResource, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result.Value), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachines.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachines.go index 8e60d5074618..37f9f3f87864 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachines.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachines.go @@ -14,12 +14,13 @@ package compute // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -42,33 +43,36 @@ func NewVirtualMachinesClientWithBaseURI(baseURI string, subscriptionID string) } // Capture captures the VM by copying VirtualHardDisks of the VM and outputs a -// template that can be used to create similar VMs. +// template that can be used to create similar VMs. This method may poll for +// completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. // // resourceGroupName is the name of the resource group. vmName is the name of // the virtual machine. parameters is parameters supplied to the Capture // Virtual Machine operation. -func (client VirtualMachinesClient) Capture(resourceGroupName string, vmName string, parameters VirtualMachineCaptureParameters) (result VirtualMachineCaptureResult, ae error) { - req, err := client.CapturePreparer(resourceGroupName, vmName, parameters) +func (client VirtualMachinesClient) Capture(resourceGroupName string, vmName string, parameters VirtualMachineCaptureParameters, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CapturePreparer(resourceGroupName, vmName, parameters, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "Capture", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Capture", nil, "Failure preparing request") } resp, err := client.CaptureSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "Capture", resp.StatusCode, "Failure sending request") + result.Response = resp + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Capture", resp, "Failure sending request") } result, err = client.CaptureResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "Capture", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Capture", resp, "Failure responding to request") } return } // CapturePreparer prepares the Capture request. -func (client VirtualMachinesClient) CapturePreparer(resourceGroupName string, vmName string, parameters VirtualMachineCaptureParameters) (*http.Request, error) { +func (client VirtualMachinesClient) CapturePreparer(resourceGroupName string, vmName string, parameters VirtualMachineCaptureParameters, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "subscriptionId": url.QueryEscape(client.SubscriptionID), @@ -79,7 +83,7 @@ func (client VirtualMachinesClient) CapturePreparer(resourceGroupName string, vm "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), @@ -92,49 +96,53 @@ func (client VirtualMachinesClient) CapturePreparer(resourceGroupName string, vm // CaptureSender sends the Capture request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachinesClient) CaptureSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // CaptureResponder handles the response to the Capture request. The method always // closes the http.Response Body. -func (client VirtualMachinesClient) CaptureResponder(resp *http.Response) (result VirtualMachineCaptureResult, err error) { +func (client VirtualMachinesClient) CaptureResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + result.Response = resp return } -// CreateOrUpdate the operation to create or update a virtual machine. +// CreateOrUpdate the operation to create or update a virtual machine. This +// method may poll for completion. Polling can be canceled by passing the +// cancel channel argument. The channel will be used to cancel polling and +// any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. vmName is the name of // the virtual machine. parameters is parameters supplied to the Create // Virtual Machine operation. -func (client VirtualMachinesClient) CreateOrUpdate(resourceGroupName string, vmName string, parameters VirtualMachine) (result VirtualMachine, ae error) { - req, err := client.CreateOrUpdatePreparer(resourceGroupName, vmName, parameters) +func (client VirtualMachinesClient) CreateOrUpdate(resourceGroupName string, vmName string, parameters VirtualMachine, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, vmName, parameters, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "CreateOrUpdate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "CreateOrUpdate", nil, "Failure preparing request") } resp, err := client.CreateOrUpdateSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "CreateOrUpdate", resp.StatusCode, "Failure sending request") + result.Response = resp + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "CreateOrUpdate", resp, "Failure sending request") } result, err = client.CreateOrUpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "CreateOrUpdate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "CreateOrUpdate", resp, "Failure responding to request") } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualMachinesClient) CreateOrUpdatePreparer(resourceGroupName string, vmName string, parameters VirtualMachine) (*http.Request, error) { +func (client VirtualMachinesClient) CreateOrUpdatePreparer(resourceGroupName string, vmName string, parameters VirtualMachine, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "subscriptionId": url.QueryEscape(client.SubscriptionID), @@ -145,7 +153,7 @@ func (client VirtualMachinesClient) CreateOrUpdatePreparer(resourceGroupName str "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), @@ -158,50 +166,53 @@ func (client VirtualMachinesClient) CreateOrUpdatePreparer(resourceGroupName str // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachinesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusCreated, http.StatusOK) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client VirtualMachinesClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualMachine, err error) { +func (client VirtualMachinesClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), - autorest.ByUnmarshallingJSON(&result), + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + result.Response = resp return } // Deallocate shuts down the Virtual Machine and releases the compute // resources. You are not billed for the compute resources that this Virtual -// Machine uses. +// Machine uses. This method may poll for completion. Polling can be canceled +// by passing the cancel channel argument. The channel will be used to cancel +// polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. vmName is the name of // the virtual machine. -func (client VirtualMachinesClient) Deallocate(resourceGroupName string, vmName string) (result autorest.Response, ae error) { - req, err := client.DeallocatePreparer(resourceGroupName, vmName) +func (client VirtualMachinesClient) Deallocate(resourceGroupName string, vmName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeallocatePreparer(resourceGroupName, vmName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "Deallocate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Deallocate", nil, "Failure preparing request") } resp, err := client.DeallocateSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "Deallocate", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Deallocate", resp, "Failure sending request") } result, err = client.DeallocateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "Deallocate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Deallocate", resp, "Failure responding to request") } return } // DeallocatePreparer prepares the Deallocate request. -func (client VirtualMachinesClient) DeallocatePreparer(resourceGroupName string, vmName string) (*http.Request, error) { +func (client VirtualMachinesClient) DeallocatePreparer(resourceGroupName string, vmName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "subscriptionId": url.QueryEscape(client.SubscriptionID), @@ -212,7 +223,7 @@ func (client VirtualMachinesClient) DeallocatePreparer(resourceGroupName string, "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), @@ -224,7 +235,9 @@ func (client VirtualMachinesClient) DeallocatePreparer(resourceGroupName string, // DeallocateSender sends the Deallocate request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachinesClient) DeallocateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // DeallocateResponder handles the response to the Deallocate request. The method always @@ -233,38 +246,41 @@ func (client VirtualMachinesClient) DeallocateResponder(resp *http.Response) (re err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } -// Delete the operation to delete a virtual machine. +// Delete the operation to delete a virtual machine. This method may poll for +// completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. // // resourceGroupName is the name of the resource group. vmName is the name of // the virtual machine. -func (client VirtualMachinesClient) Delete(resourceGroupName string, vmName string) (result autorest.Response, ae error) { - req, err := client.DeletePreparer(resourceGroupName, vmName) +func (client VirtualMachinesClient) Delete(resourceGroupName string, vmName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, vmName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "Delete", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Delete", nil, "Failure preparing request") } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "Delete", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Delete", resp, "Failure sending request") } result, err = client.DeleteResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "Delete", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Delete", resp, "Failure responding to request") } return } // DeletePreparer prepares the Delete request. -func (client VirtualMachinesClient) DeletePreparer(resourceGroupName string, vmName string) (*http.Request, error) { +func (client VirtualMachinesClient) DeletePreparer(resourceGroupName string, vmName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "subscriptionId": url.QueryEscape(client.SubscriptionID), @@ -275,7 +291,7 @@ func (client VirtualMachinesClient) DeletePreparer(resourceGroupName string, vmN "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), @@ -287,7 +303,9 @@ func (client VirtualMachinesClient) DeletePreparer(resourceGroupName string, vmN // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachinesClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted, http.StatusNoContent) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // DeleteResponder handles the response to the Delete request. The method always @@ -296,7 +314,7 @@ func (client VirtualMachinesClient) DeleteResponder(resp *http.Response) (result err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return @@ -306,21 +324,21 @@ func (client VirtualMachinesClient) DeleteResponder(resp *http.Response) (result // // resourceGroupName is the name of the resource group. vmName is the name of // the virtual machine. -func (client VirtualMachinesClient) Generalize(resourceGroupName string, vmName string) (result autorest.Response, ae error) { +func (client VirtualMachinesClient) Generalize(resourceGroupName string, vmName string) (result autorest.Response, err error) { req, err := client.GeneralizePreparer(resourceGroupName, vmName) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "Generalize", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Generalize", nil, "Failure preparing request") } resp, err := client.GeneralizeSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "Generalize", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Generalize", resp, "Failure sending request") } result, err = client.GeneralizeResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "Generalize", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Generalize", resp, "Failure responding to request") } return @@ -350,7 +368,7 @@ func (client VirtualMachinesClient) GeneralizePreparer(resourceGroupName string, // GeneralizeSender sends the Generalize request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachinesClient) GeneralizeSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GeneralizeResponder handles the response to the Generalize request. The method always @@ -359,7 +377,7 @@ func (client VirtualMachinesClient) GeneralizeResponder(resp *http.Response) (re err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByClosing()) result.Response = resp return @@ -370,21 +388,21 @@ func (client VirtualMachinesClient) GeneralizeResponder(resp *http.Response) (re // resourceGroupName is the name of the resource group. vmName is the name of // the virtual machine. expand is the expand expression to apply on the // operation. -func (client VirtualMachinesClient) Get(resourceGroupName string, vmName string, expand string) (result VirtualMachine, ae error) { +func (client VirtualMachinesClient) Get(resourceGroupName string, vmName string, expand string) (result VirtualMachine, err error) { req, err := client.GetPreparer(resourceGroupName, vmName, expand) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Get", resp, "Failure responding to request") } return @@ -417,7 +435,7 @@ func (client VirtualMachinesClient) GetPreparer(resourceGroupName string, vmName // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachinesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -426,7 +444,7 @@ func (client VirtualMachinesClient) GetResponder(resp *http.Response) (result Vi err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -436,21 +454,21 @@ func (client VirtualMachinesClient) GetResponder(resp *http.Response) (result Vi // List the operation to list virtual machines under a resource group. // // resourceGroupName is the name of the resource group. -func (client VirtualMachinesClient) List(resourceGroupName string) (result VirtualMachineListResult, ae error) { +func (client VirtualMachinesClient) List(resourceGroupName string) (result VirtualMachineListResult, err error) { req, err := client.ListPreparer(resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "List", resp, "Failure responding to request") } return @@ -479,7 +497,7 @@ func (client VirtualMachinesClient) ListPreparer(resourceGroupName string) (*htt // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachinesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -488,7 +506,7 @@ func (client VirtualMachinesClient) ListResponder(resp *http.Response) (result V err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -496,10 +514,10 @@ func (client VirtualMachinesClient) ListResponder(resp *http.Response) (result V } // ListNextResults retrieves the next set of results, if any. -func (client VirtualMachinesClient) ListNextResults(lastResults VirtualMachineListResult) (result VirtualMachineListResult, ae error) { +func (client VirtualMachinesClient) ListNextResults(lastResults VirtualMachineListResult) (result VirtualMachineListResult, err error) { req, err := lastResults.VirtualMachineListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -508,12 +526,12 @@ func (client VirtualMachinesClient) ListNextResults(lastResults VirtualMachineLi resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "List", resp, "Failure responding to next results request request") } return @@ -522,21 +540,21 @@ func (client VirtualMachinesClient) ListNextResults(lastResults VirtualMachineLi // ListAll gets the list of Virtual Machines in the subscription. Use nextLink // property in the response to get the next page of Virtual Machines. Do this // till nextLink is not null to fetch all the Virtual Machines. -func (client VirtualMachinesClient) ListAll() (result VirtualMachineListResult, ae error) { +func (client VirtualMachinesClient) ListAll() (result VirtualMachineListResult, err error) { req, err := client.ListAllPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "ListAll", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAll", nil, "Failure preparing request") } resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "ListAll", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAll", resp, "Failure sending request") } result, err = client.ListAllResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "ListAll", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAll", resp, "Failure responding to request") } return @@ -564,7 +582,7 @@ func (client VirtualMachinesClient) ListAllPreparer() (*http.Request, error) { // ListAllSender sends the ListAll request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachinesClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListAllResponder handles the response to the ListAll request. The method always @@ -573,7 +591,7 @@ func (client VirtualMachinesClient) ListAllResponder(resp *http.Response) (resul err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -581,10 +599,10 @@ func (client VirtualMachinesClient) ListAllResponder(resp *http.Response) (resul } // ListAllNextResults retrieves the next set of results, if any. -func (client VirtualMachinesClient) ListAllNextResults(lastResults VirtualMachineListResult) (result VirtualMachineListResult, ae error) { +func (client VirtualMachinesClient) ListAllNextResults(lastResults VirtualMachineListResult) (result VirtualMachineListResult, err error) { req, err := lastResults.VirtualMachineListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "ListAll", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAll", nil, "Failure preparing next results request request") } if req == nil { return @@ -593,12 +611,12 @@ func (client VirtualMachinesClient) ListAllNextResults(lastResults VirtualMachin resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "ListAll", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAll", resp, "Failure sending next results request request") } result, err = client.ListAllResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "ListAll", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAll", resp, "Failure responding to next results request request") } return @@ -609,21 +627,21 @@ func (client VirtualMachinesClient) ListAllNextResults(lastResults VirtualMachin // // resourceGroupName is the name of the resource group. vmName is the name of // the virtual machine. -func (client VirtualMachinesClient) ListAvailableSizes(resourceGroupName string, vmName string) (result VirtualMachineSizeListResult, ae error) { +func (client VirtualMachinesClient) ListAvailableSizes(resourceGroupName string, vmName string) (result VirtualMachineSizeListResult, err error) { req, err := client.ListAvailableSizesPreparer(resourceGroupName, vmName) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "ListAvailableSizes", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAvailableSizes", nil, "Failure preparing request") } resp, err := client.ListAvailableSizesSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "ListAvailableSizes", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAvailableSizes", resp, "Failure sending request") } result, err = client.ListAvailableSizesResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "ListAvailableSizes", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAvailableSizes", resp, "Failure responding to request") } return @@ -653,7 +671,7 @@ func (client VirtualMachinesClient) ListAvailableSizesPreparer(resourceGroupName // ListAvailableSizesSender sends the ListAvailableSizes request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachinesClient) ListAvailableSizesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListAvailableSizesResponder handles the response to the ListAvailableSizes request. The method always @@ -662,7 +680,7 @@ func (client VirtualMachinesClient) ListAvailableSizesResponder(resp *http.Respo err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -670,10 +688,10 @@ func (client VirtualMachinesClient) ListAvailableSizesResponder(resp *http.Respo } // ListAvailableSizesNextResults retrieves the next set of results, if any. -func (client VirtualMachinesClient) ListAvailableSizesNextResults(lastResults VirtualMachineSizeListResult) (result VirtualMachineSizeListResult, ae error) { +func (client VirtualMachinesClient) ListAvailableSizesNextResults(lastResults VirtualMachineSizeListResult) (result VirtualMachineSizeListResult, err error) { req, err := lastResults.VirtualMachineSizeListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "ListAvailableSizes", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAvailableSizes", nil, "Failure preparing next results request request") } if req == nil { return @@ -682,43 +700,46 @@ func (client VirtualMachinesClient) ListAvailableSizesNextResults(lastResults Vi resp, err := client.ListAvailableSizesSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "ListAvailableSizes", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAvailableSizes", resp, "Failure sending next results request request") } result, err = client.ListAvailableSizesResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "ListAvailableSizes", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAvailableSizes", resp, "Failure responding to next results request request") } return } -// PowerOff the operation to power off (stop) a virtual machine. +// PowerOff the operation to power off (stop) a virtual machine. This method +// may poll for completion. Polling can be canceled by passing the cancel +// channel argument. The channel will be used to cancel polling and any +// outstanding HTTP requests. // // resourceGroupName is the name of the resource group. vmName is the name of // the virtual machine. -func (client VirtualMachinesClient) PowerOff(resourceGroupName string, vmName string) (result autorest.Response, ae error) { - req, err := client.PowerOffPreparer(resourceGroupName, vmName) +func (client VirtualMachinesClient) PowerOff(resourceGroupName string, vmName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.PowerOffPreparer(resourceGroupName, vmName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "PowerOff", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "PowerOff", nil, "Failure preparing request") } resp, err := client.PowerOffSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "PowerOff", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "PowerOff", resp, "Failure sending request") } result, err = client.PowerOffResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "PowerOff", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "PowerOff", resp, "Failure responding to request") } return } // PowerOffPreparer prepares the PowerOff request. -func (client VirtualMachinesClient) PowerOffPreparer(resourceGroupName string, vmName string) (*http.Request, error) { +func (client VirtualMachinesClient) PowerOffPreparer(resourceGroupName string, vmName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "subscriptionId": url.QueryEscape(client.SubscriptionID), @@ -729,7 +750,7 @@ func (client VirtualMachinesClient) PowerOffPreparer(resourceGroupName string, v "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), @@ -741,7 +762,9 @@ func (client VirtualMachinesClient) PowerOffPreparer(resourceGroupName string, v // PowerOffSender sends the PowerOff request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachinesClient) PowerOffSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // PowerOffResponder handles the response to the PowerOff request. The method always @@ -750,38 +773,41 @@ func (client VirtualMachinesClient) PowerOffResponder(resp *http.Response) (resu err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } -// Restart the operation to restart a virtual machine. +// Restart the operation to restart a virtual machine. This method may poll +// for completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. // // resourceGroupName is the name of the resource group. vmName is the name of // the virtual machine. -func (client VirtualMachinesClient) Restart(resourceGroupName string, vmName string) (result autorest.Response, ae error) { - req, err := client.RestartPreparer(resourceGroupName, vmName) +func (client VirtualMachinesClient) Restart(resourceGroupName string, vmName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.RestartPreparer(resourceGroupName, vmName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "Restart", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Restart", nil, "Failure preparing request") } resp, err := client.RestartSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "Restart", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Restart", resp, "Failure sending request") } result, err = client.RestartResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "Restart", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Restart", resp, "Failure responding to request") } return } // RestartPreparer prepares the Restart request. -func (client VirtualMachinesClient) RestartPreparer(resourceGroupName string, vmName string) (*http.Request, error) { +func (client VirtualMachinesClient) RestartPreparer(resourceGroupName string, vmName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "subscriptionId": url.QueryEscape(client.SubscriptionID), @@ -792,7 +818,7 @@ func (client VirtualMachinesClient) RestartPreparer(resourceGroupName string, vm "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), @@ -804,7 +830,9 @@ func (client VirtualMachinesClient) RestartPreparer(resourceGroupName string, vm // RestartSender sends the Restart request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachinesClient) RestartSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // RestartResponder handles the response to the Restart request. The method always @@ -813,38 +841,41 @@ func (client VirtualMachinesClient) RestartResponder(resp *http.Response) (resul err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } -// Start the operation to start a virtual machine. +// Start the operation to start a virtual machine. This method may poll for +// completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. // // resourceGroupName is the name of the resource group. vmName is the name of // the virtual machine. -func (client VirtualMachinesClient) Start(resourceGroupName string, vmName string) (result autorest.Response, ae error) { - req, err := client.StartPreparer(resourceGroupName, vmName) +func (client VirtualMachinesClient) Start(resourceGroupName string, vmName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.StartPreparer(resourceGroupName, vmName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "Start", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Start", nil, "Failure preparing request") } resp, err := client.StartSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "Start", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Start", resp, "Failure sending request") } result, err = client.StartResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachinesClient", "Start", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Start", resp, "Failure responding to request") } return } // StartPreparer prepares the Start request. -func (client VirtualMachinesClient) StartPreparer(resourceGroupName string, vmName string) (*http.Request, error) { +func (client VirtualMachinesClient) StartPreparer(resourceGroupName string, vmName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "subscriptionId": url.QueryEscape(client.SubscriptionID), @@ -855,7 +886,7 @@ func (client VirtualMachinesClient) StartPreparer(resourceGroupName string, vmNa "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), @@ -867,7 +898,9 @@ func (client VirtualMachinesClient) StartPreparer(resourceGroupName string, vmNa // StartSender sends the Start request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachinesClient) StartSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // StartResponder handles the response to the Start request. The method always @@ -876,7 +909,7 @@ func (client VirtualMachinesClient) StartResponder(resp *http.Response) (result err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachinescalesets.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachinescalesets.go index 462121ee2369..7fedc2754a3e 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachinescalesets.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachinescalesets.go @@ -14,12 +14,13 @@ package compute // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -42,33 +43,35 @@ func NewVirtualMachineScaleSetsClientWithBaseURI(baseURI string, subscriptionID } // CreateOrUpdate the operation to create or update a virtual machine scale -// set. +// set. This method may poll for completion. Polling can be canceled by +// passing the cancel channel argument. The channel will be used to cancel +// polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. name is parameters // supplied to the Create Virtual Machine Scale Set operation. parameters is // parameters supplied to the Create Virtual Machine Scale Set operation. -func (client VirtualMachineScaleSetsClient) CreateOrUpdate(resourceGroupName string, name string, parameters VirtualMachineScaleSet) (result VirtualMachineScaleSet, ae error) { - req, err := client.CreateOrUpdatePreparer(resourceGroupName, name, parameters) +func (client VirtualMachineScaleSetsClient) CreateOrUpdate(resourceGroupName string, name string, parameters VirtualMachineScaleSet, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, name, parameters, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "CreateOrUpdate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "CreateOrUpdate", nil, "Failure preparing request") } resp, err := client.CreateOrUpdateSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "CreateOrUpdate", resp.StatusCode, "Failure sending request") + result.Response = resp + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "CreateOrUpdate", resp, "Failure sending request") } result, err = client.CreateOrUpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "CreateOrUpdate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "CreateOrUpdate", resp, "Failure responding to request") } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualMachineScaleSetsClient) CreateOrUpdatePreparer(resourceGroupName string, name string, parameters VirtualMachineScaleSet) (*http.Request, error) { +func (client VirtualMachineScaleSetsClient) CreateOrUpdatePreparer(resourceGroupName string, name string, parameters VirtualMachineScaleSet, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "name": url.QueryEscape(name), "resourceGroupName": url.QueryEscape(resourceGroupName), @@ -79,7 +82,7 @@ func (client VirtualMachineScaleSetsClient) CreateOrUpdatePreparer(resourceGroup "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), @@ -92,50 +95,53 @@ func (client VirtualMachineScaleSetsClient) CreateOrUpdatePreparer(resourceGroup // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusCreated, http.StatusOK) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client VirtualMachineScaleSetsClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualMachineScaleSet, err error) { +func (client VirtualMachineScaleSetsClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), - autorest.ByUnmarshallingJSON(&result), + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + result.Response = resp return } // Deallocate the operation to deallocate virtual machines in a virtual -// machine scale set. +// machine scale set. This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. vmScaleSetName is the // name of the virtual machine scale set. vmInstanceIDs is the list of // virtual machine scale set instance IDs. -func (client VirtualMachineScaleSetsClient) Deallocate(resourceGroupName string, vmScaleSetName string, vmInstanceIDs *VirtualMachineScaleSetVMInstanceIDs) (result autorest.Response, ae error) { - req, err := client.DeallocatePreparer(resourceGroupName, vmScaleSetName, vmInstanceIDs) +func (client VirtualMachineScaleSetsClient) Deallocate(resourceGroupName string, vmScaleSetName string, vmInstanceIDs *VirtualMachineScaleSetVMInstanceIDs, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeallocatePreparer(resourceGroupName, vmScaleSetName, vmInstanceIDs, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "Deallocate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Deallocate", nil, "Failure preparing request") } resp, err := client.DeallocateSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "Deallocate", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Deallocate", resp, "Failure sending request") } result, err = client.DeallocateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "Deallocate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Deallocate", resp, "Failure responding to request") } return } // DeallocatePreparer prepares the Deallocate request. -func (client VirtualMachineScaleSetsClient) DeallocatePreparer(resourceGroupName string, vmScaleSetName string, vmInstanceIDs *VirtualMachineScaleSetVMInstanceIDs) (*http.Request, error) { +func (client VirtualMachineScaleSetsClient) DeallocatePreparer(resourceGroupName string, vmScaleSetName string, vmInstanceIDs *VirtualMachineScaleSetVMInstanceIDs, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "subscriptionId": url.QueryEscape(client.SubscriptionID), @@ -157,13 +163,15 @@ func (client VirtualMachineScaleSetsClient) DeallocatePreparer(resourceGroupName preparer = autorest.DecoratePreparer(preparer, autorest.WithJSON(vmInstanceIDs)) } - return preparer.Prepare(&http.Request{}) + return preparer.Prepare(&http.Request{Cancel: cancel}) } // DeallocateSender sends the Deallocate request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetsClient) DeallocateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // DeallocateResponder handles the response to the Deallocate request. The method always @@ -172,38 +180,41 @@ func (client VirtualMachineScaleSetsClient) DeallocateResponder(resp *http.Respo err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } -// Delete the operation to delete a virtual machine scale set. +// Delete the operation to delete a virtual machine scale set. This method may +// poll for completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. // // resourceGroupName is the name of the resource group. vmScaleSetName is the // name of the virtual machine scale set. -func (client VirtualMachineScaleSetsClient) Delete(resourceGroupName string, vmScaleSetName string) (result autorest.Response, ae error) { - req, err := client.DeletePreparer(resourceGroupName, vmScaleSetName) +func (client VirtualMachineScaleSetsClient) Delete(resourceGroupName string, vmScaleSetName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, vmScaleSetName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "Delete", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Delete", nil, "Failure preparing request") } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "Delete", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Delete", resp, "Failure sending request") } result, err = client.DeleteResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "Delete", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Delete", resp, "Failure responding to request") } return } // DeletePreparer prepares the Delete request. -func (client VirtualMachineScaleSetsClient) DeletePreparer(resourceGroupName string, vmScaleSetName string) (*http.Request, error) { +func (client VirtualMachineScaleSetsClient) DeletePreparer(resourceGroupName string, vmScaleSetName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "subscriptionId": url.QueryEscape(client.SubscriptionID), @@ -214,7 +225,7 @@ func (client VirtualMachineScaleSetsClient) DeletePreparer(resourceGroupName str "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), @@ -226,7 +237,9 @@ func (client VirtualMachineScaleSetsClient) DeletePreparer(resourceGroupName str // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusAccepted, http.StatusOK, http.StatusNoContent) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // DeleteResponder handles the response to the Delete request. The method always @@ -235,40 +248,42 @@ func (client VirtualMachineScaleSetsClient) DeleteResponder(resp *http.Response) err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusOK, http.StatusNoContent), + azure.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusOK, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return } // DeleteInstances the operation to delete virtual machines in a virtual -// machine scale set. +// machine scale set. This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. vmScaleSetName is the // name of the virtual machine scale set. vmInstanceIDs is the list of // virtual machine scale set instance IDs. -func (client VirtualMachineScaleSetsClient) DeleteInstances(resourceGroupName string, vmScaleSetName string, vmInstanceIDs VirtualMachineScaleSetVMInstanceRequiredIDs) (result autorest.Response, ae error) { - req, err := client.DeleteInstancesPreparer(resourceGroupName, vmScaleSetName, vmInstanceIDs) +func (client VirtualMachineScaleSetsClient) DeleteInstances(resourceGroupName string, vmScaleSetName string, vmInstanceIDs VirtualMachineScaleSetVMInstanceRequiredIDs, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeleteInstancesPreparer(resourceGroupName, vmScaleSetName, vmInstanceIDs, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "DeleteInstances", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "DeleteInstances", nil, "Failure preparing request") } resp, err := client.DeleteInstancesSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "DeleteInstances", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "DeleteInstances", resp, "Failure sending request") } result, err = client.DeleteInstancesResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "DeleteInstances", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "DeleteInstances", resp, "Failure responding to request") } return } // DeleteInstancesPreparer prepares the DeleteInstances request. -func (client VirtualMachineScaleSetsClient) DeleteInstancesPreparer(resourceGroupName string, vmScaleSetName string, vmInstanceIDs VirtualMachineScaleSetVMInstanceRequiredIDs) (*http.Request, error) { +func (client VirtualMachineScaleSetsClient) DeleteInstancesPreparer(resourceGroupName string, vmScaleSetName string, vmInstanceIDs VirtualMachineScaleSetVMInstanceRequiredIDs, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "subscriptionId": url.QueryEscape(client.SubscriptionID), @@ -279,7 +294,7 @@ func (client VirtualMachineScaleSetsClient) DeleteInstancesPreparer(resourceGrou "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), @@ -292,7 +307,9 @@ func (client VirtualMachineScaleSetsClient) DeleteInstancesPreparer(resourceGrou // DeleteInstancesSender sends the DeleteInstances request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetsClient) DeleteInstancesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // DeleteInstancesResponder handles the response to the DeleteInstances request. The method always @@ -301,7 +318,7 @@ func (client VirtualMachineScaleSetsClient) DeleteInstancesResponder(resp *http. err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return @@ -311,21 +328,21 @@ func (client VirtualMachineScaleSetsClient) DeleteInstancesResponder(resp *http. // // resourceGroupName is the name of the resource group. vmScaleSetName is the // name of the virtual machine scale set. -func (client VirtualMachineScaleSetsClient) Get(resourceGroupName string, vmScaleSetName string) (result VirtualMachineScaleSet, ae error) { +func (client VirtualMachineScaleSetsClient) Get(resourceGroupName string, vmScaleSetName string) (result VirtualMachineScaleSet, err error) { req, err := client.GetPreparer(resourceGroupName, vmScaleSetName) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Get", resp, "Failure responding to request") } return @@ -355,7 +372,7 @@ func (client VirtualMachineScaleSetsClient) GetPreparer(resourceGroupName string // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -364,7 +381,7 @@ func (client VirtualMachineScaleSetsClient) GetResponder(resp *http.Response) (r err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -376,21 +393,21 @@ func (client VirtualMachineScaleSetsClient) GetResponder(resp *http.Response) (r // // resourceGroupName is the name of the resource group. vmScaleSetName is the // name of the virtual machine scale set. -func (client VirtualMachineScaleSetsClient) GetInstanceView(resourceGroupName string, vmScaleSetName string) (result VirtualMachineScaleSetInstanceView, ae error) { +func (client VirtualMachineScaleSetsClient) GetInstanceView(resourceGroupName string, vmScaleSetName string) (result VirtualMachineScaleSetInstanceView, err error) { req, err := client.GetInstanceViewPreparer(resourceGroupName, vmScaleSetName) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "GetInstanceView", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "GetInstanceView", nil, "Failure preparing request") } resp, err := client.GetInstanceViewSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "GetInstanceView", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "GetInstanceView", resp, "Failure sending request") } result, err = client.GetInstanceViewResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "GetInstanceView", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "GetInstanceView", resp, "Failure responding to request") } return @@ -420,7 +437,7 @@ func (client VirtualMachineScaleSetsClient) GetInstanceViewPreparer(resourceGrou // GetInstanceViewSender sends the GetInstanceView request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetsClient) GetInstanceViewSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetInstanceViewResponder handles the response to the GetInstanceView request. The method always @@ -429,7 +446,7 @@ func (client VirtualMachineScaleSetsClient) GetInstanceViewResponder(resp *http. err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -440,21 +457,21 @@ func (client VirtualMachineScaleSetsClient) GetInstanceViewResponder(resp *http. // group. // // resourceGroupName is the name of the resource group. -func (client VirtualMachineScaleSetsClient) List(resourceGroupName string) (result VirtualMachineScaleSetListResult, ae error) { +func (client VirtualMachineScaleSetsClient) List(resourceGroupName string) (result VirtualMachineScaleSetListResult, err error) { req, err := client.ListPreparer(resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "List", resp, "Failure responding to request") } return @@ -483,7 +500,7 @@ func (client VirtualMachineScaleSetsClient) ListPreparer(resourceGroupName strin // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -492,7 +509,7 @@ func (client VirtualMachineScaleSetsClient) ListResponder(resp *http.Response) ( err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -500,10 +517,10 @@ func (client VirtualMachineScaleSetsClient) ListResponder(resp *http.Response) ( } // ListNextResults retrieves the next set of results, if any. -func (client VirtualMachineScaleSetsClient) ListNextResults(lastResults VirtualMachineScaleSetListResult) (result VirtualMachineScaleSetListResult, ae error) { +func (client VirtualMachineScaleSetsClient) ListNextResults(lastResults VirtualMachineScaleSetListResult) (result VirtualMachineScaleSetListResult, err error) { req, err := lastResults.VirtualMachineScaleSetListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -512,12 +529,12 @@ func (client VirtualMachineScaleSetsClient) ListNextResults(lastResults VirtualM resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "List", resp, "Failure responding to next results request request") } return @@ -527,21 +544,21 @@ func (client VirtualMachineScaleSetsClient) ListNextResults(lastResults VirtualM // Use nextLink property in the response to get the next page of Virtual // Machine Scale Sets. Do this till nextLink is not null to fetch all the // Virtual Machine Scale Sets. -func (client VirtualMachineScaleSetsClient) ListAll() (result VirtualMachineScaleSetListWithLinkResult, ae error) { +func (client VirtualMachineScaleSetsClient) ListAll() (result VirtualMachineScaleSetListWithLinkResult, err error) { req, err := client.ListAllPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "ListAll", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListAll", nil, "Failure preparing request") } resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "ListAll", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListAll", resp, "Failure sending request") } result, err = client.ListAllResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "ListAll", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListAll", resp, "Failure responding to request") } return @@ -569,7 +586,7 @@ func (client VirtualMachineScaleSetsClient) ListAllPreparer() (*http.Request, er // ListAllSender sends the ListAll request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetsClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListAllResponder handles the response to the ListAll request. The method always @@ -578,7 +595,7 @@ func (client VirtualMachineScaleSetsClient) ListAllResponder(resp *http.Response err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -586,10 +603,10 @@ func (client VirtualMachineScaleSetsClient) ListAllResponder(resp *http.Response } // ListAllNextResults retrieves the next set of results, if any. -func (client VirtualMachineScaleSetsClient) ListAllNextResults(lastResults VirtualMachineScaleSetListWithLinkResult) (result VirtualMachineScaleSetListWithLinkResult, ae error) { +func (client VirtualMachineScaleSetsClient) ListAllNextResults(lastResults VirtualMachineScaleSetListWithLinkResult) (result VirtualMachineScaleSetListWithLinkResult, err error) { req, err := lastResults.VirtualMachineScaleSetListWithLinkResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "ListAll", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListAll", nil, "Failure preparing next results request request") } if req == nil { return @@ -598,12 +615,12 @@ func (client VirtualMachineScaleSetsClient) ListAllNextResults(lastResults Virtu resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "ListAll", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListAll", resp, "Failure sending next results request request") } result, err = client.ListAllResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "ListAll", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListAll", resp, "Failure responding to next results request request") } return @@ -614,21 +631,21 @@ func (client VirtualMachineScaleSetsClient) ListAllNextResults(lastResults Virtu // // resourceGroupName is the name of the resource group. vmScaleSetName is the // name of the virtual machine scale set. -func (client VirtualMachineScaleSetsClient) ListSkus(resourceGroupName string, vmScaleSetName string) (result VirtualMachineScaleSetListSkusResult, ae error) { +func (client VirtualMachineScaleSetsClient) ListSkus(resourceGroupName string, vmScaleSetName string) (result VirtualMachineScaleSetListSkusResult, err error) { req, err := client.ListSkusPreparer(resourceGroupName, vmScaleSetName) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "ListSkus", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListSkus", nil, "Failure preparing request") } resp, err := client.ListSkusSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "ListSkus", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListSkus", resp, "Failure sending request") } result, err = client.ListSkusResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "ListSkus", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListSkus", resp, "Failure responding to request") } return @@ -658,7 +675,7 @@ func (client VirtualMachineScaleSetsClient) ListSkusPreparer(resourceGroupName s // ListSkusSender sends the ListSkus request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetsClient) ListSkusSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListSkusResponder handles the response to the ListSkus request. The method always @@ -667,7 +684,7 @@ func (client VirtualMachineScaleSetsClient) ListSkusResponder(resp *http.Respons err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -675,10 +692,10 @@ func (client VirtualMachineScaleSetsClient) ListSkusResponder(resp *http.Respons } // ListSkusNextResults retrieves the next set of results, if any. -func (client VirtualMachineScaleSetsClient) ListSkusNextResults(lastResults VirtualMachineScaleSetListSkusResult) (result VirtualMachineScaleSetListSkusResult, ae error) { +func (client VirtualMachineScaleSetsClient) ListSkusNextResults(lastResults VirtualMachineScaleSetListSkusResult) (result VirtualMachineScaleSetListSkusResult, err error) { req, err := lastResults.VirtualMachineScaleSetListSkusResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "ListSkus", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListSkus", nil, "Failure preparing next results request request") } if req == nil { return @@ -687,45 +704,47 @@ func (client VirtualMachineScaleSetsClient) ListSkusNextResults(lastResults Virt resp, err := client.ListSkusSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "ListSkus", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListSkus", resp, "Failure sending next results request request") } result, err = client.ListSkusResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "ListSkus", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListSkus", resp, "Failure responding to next results request request") } return } // PowerOff the operation to power off (stop) virtual machines in a virtual -// machine scale set. +// machine scale set. This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. vmScaleSetName is the // name of the virtual machine scale set. vmInstanceIDs is the list of // virtual machine scale set instance IDs. -func (client VirtualMachineScaleSetsClient) PowerOff(resourceGroupName string, vmScaleSetName string, vmInstanceIDs *VirtualMachineScaleSetVMInstanceIDs) (result autorest.Response, ae error) { - req, err := client.PowerOffPreparer(resourceGroupName, vmScaleSetName, vmInstanceIDs) +func (client VirtualMachineScaleSetsClient) PowerOff(resourceGroupName string, vmScaleSetName string, vmInstanceIDs *VirtualMachineScaleSetVMInstanceIDs, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.PowerOffPreparer(resourceGroupName, vmScaleSetName, vmInstanceIDs, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "PowerOff", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "PowerOff", nil, "Failure preparing request") } resp, err := client.PowerOffSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "PowerOff", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "PowerOff", resp, "Failure sending request") } result, err = client.PowerOffResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "PowerOff", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "PowerOff", resp, "Failure responding to request") } return } // PowerOffPreparer prepares the PowerOff request. -func (client VirtualMachineScaleSetsClient) PowerOffPreparer(resourceGroupName string, vmScaleSetName string, vmInstanceIDs *VirtualMachineScaleSetVMInstanceIDs) (*http.Request, error) { +func (client VirtualMachineScaleSetsClient) PowerOffPreparer(resourceGroupName string, vmScaleSetName string, vmInstanceIDs *VirtualMachineScaleSetVMInstanceIDs, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "subscriptionId": url.QueryEscape(client.SubscriptionID), @@ -747,13 +766,15 @@ func (client VirtualMachineScaleSetsClient) PowerOffPreparer(resourceGroupName s preparer = autorest.DecoratePreparer(preparer, autorest.WithJSON(vmInstanceIDs)) } - return preparer.Prepare(&http.Request{}) + return preparer.Prepare(&http.Request{Cancel: cancel}) } // PowerOffSender sends the PowerOff request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetsClient) PowerOffSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // PowerOffResponder handles the response to the PowerOff request. The method always @@ -762,40 +783,42 @@ func (client VirtualMachineScaleSetsClient) PowerOffResponder(resp *http.Respons err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } // Restart the operation to restart virtual machines in a virtual machine -// scale set. +// scale set. This method may poll for completion. Polling can be canceled by +// passing the cancel channel argument. The channel will be used to cancel +// polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. vmScaleSetName is the // name of the virtual machine scale set. vmInstanceIDs is the list of // virtual machine scale set instance IDs. -func (client VirtualMachineScaleSetsClient) Restart(resourceGroupName string, vmScaleSetName string, vmInstanceIDs *VirtualMachineScaleSetVMInstanceIDs) (result autorest.Response, ae error) { - req, err := client.RestartPreparer(resourceGroupName, vmScaleSetName, vmInstanceIDs) +func (client VirtualMachineScaleSetsClient) Restart(resourceGroupName string, vmScaleSetName string, vmInstanceIDs *VirtualMachineScaleSetVMInstanceIDs, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.RestartPreparer(resourceGroupName, vmScaleSetName, vmInstanceIDs, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "Restart", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Restart", nil, "Failure preparing request") } resp, err := client.RestartSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "Restart", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Restart", resp, "Failure sending request") } result, err = client.RestartResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "Restart", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Restart", resp, "Failure responding to request") } return } // RestartPreparer prepares the Restart request. -func (client VirtualMachineScaleSetsClient) RestartPreparer(resourceGroupName string, vmScaleSetName string, vmInstanceIDs *VirtualMachineScaleSetVMInstanceIDs) (*http.Request, error) { +func (client VirtualMachineScaleSetsClient) RestartPreparer(resourceGroupName string, vmScaleSetName string, vmInstanceIDs *VirtualMachineScaleSetVMInstanceIDs, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "subscriptionId": url.QueryEscape(client.SubscriptionID), @@ -817,13 +840,15 @@ func (client VirtualMachineScaleSetsClient) RestartPreparer(resourceGroupName st preparer = autorest.DecoratePreparer(preparer, autorest.WithJSON(vmInstanceIDs)) } - return preparer.Prepare(&http.Request{}) + return preparer.Prepare(&http.Request{Cancel: cancel}) } // RestartSender sends the Restart request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetsClient) RestartSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // RestartResponder handles the response to the Restart request. The method always @@ -832,40 +857,42 @@ func (client VirtualMachineScaleSetsClient) RestartResponder(resp *http.Response err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } // Start the operation to start virtual machines in a virtual machine scale -// set. +// set. This method may poll for completion. Polling can be canceled by +// passing the cancel channel argument. The channel will be used to cancel +// polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. vmScaleSetName is the // name of the virtual machine scale set. vmInstanceIDs is the list of // virtual machine scale set instance IDs. -func (client VirtualMachineScaleSetsClient) Start(resourceGroupName string, vmScaleSetName string, vmInstanceIDs *VirtualMachineScaleSetVMInstanceIDs) (result autorest.Response, ae error) { - req, err := client.StartPreparer(resourceGroupName, vmScaleSetName, vmInstanceIDs) +func (client VirtualMachineScaleSetsClient) Start(resourceGroupName string, vmScaleSetName string, vmInstanceIDs *VirtualMachineScaleSetVMInstanceIDs, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.StartPreparer(resourceGroupName, vmScaleSetName, vmInstanceIDs, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "Start", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Start", nil, "Failure preparing request") } resp, err := client.StartSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "Start", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Start", resp, "Failure sending request") } result, err = client.StartResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "Start", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Start", resp, "Failure responding to request") } return } // StartPreparer prepares the Start request. -func (client VirtualMachineScaleSetsClient) StartPreparer(resourceGroupName string, vmScaleSetName string, vmInstanceIDs *VirtualMachineScaleSetVMInstanceIDs) (*http.Request, error) { +func (client VirtualMachineScaleSetsClient) StartPreparer(resourceGroupName string, vmScaleSetName string, vmInstanceIDs *VirtualMachineScaleSetVMInstanceIDs, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "subscriptionId": url.QueryEscape(client.SubscriptionID), @@ -887,13 +914,15 @@ func (client VirtualMachineScaleSetsClient) StartPreparer(resourceGroupName stri preparer = autorest.DecoratePreparer(preparer, autorest.WithJSON(vmInstanceIDs)) } - return preparer.Prepare(&http.Request{}) + return preparer.Prepare(&http.Request{Cancel: cancel}) } // StartSender sends the Start request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetsClient) StartSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // StartResponder handles the response to the Start request. The method always @@ -902,40 +931,42 @@ func (client VirtualMachineScaleSetsClient) StartResponder(resp *http.Response) err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } // UpdateInstances the operation to manually upgrade virtual machines in a -// virtual machine scale set. +// virtual machine scale set. This method may poll for completion. Polling +// can be canceled by passing the cancel channel argument. The channel will +// be used to cancel polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. vmScaleSetName is the // name of the virtual machine scale set. vmInstanceIDs is the list of // virtual machine scale set instance IDs. -func (client VirtualMachineScaleSetsClient) UpdateInstances(resourceGroupName string, vmScaleSetName string, vmInstanceIDs VirtualMachineScaleSetVMInstanceRequiredIDs) (result autorest.Response, ae error) { - req, err := client.UpdateInstancesPreparer(resourceGroupName, vmScaleSetName, vmInstanceIDs) +func (client VirtualMachineScaleSetsClient) UpdateInstances(resourceGroupName string, vmScaleSetName string, vmInstanceIDs VirtualMachineScaleSetVMInstanceRequiredIDs, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.UpdateInstancesPreparer(resourceGroupName, vmScaleSetName, vmInstanceIDs, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "UpdateInstances", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "UpdateInstances", nil, "Failure preparing request") } resp, err := client.UpdateInstancesSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "UpdateInstances", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "UpdateInstances", resp, "Failure sending request") } result, err = client.UpdateInstancesResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetsClient", "UpdateInstances", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "UpdateInstances", resp, "Failure responding to request") } return } // UpdateInstancesPreparer prepares the UpdateInstances request. -func (client VirtualMachineScaleSetsClient) UpdateInstancesPreparer(resourceGroupName string, vmScaleSetName string, vmInstanceIDs VirtualMachineScaleSetVMInstanceRequiredIDs) (*http.Request, error) { +func (client VirtualMachineScaleSetsClient) UpdateInstancesPreparer(resourceGroupName string, vmScaleSetName string, vmInstanceIDs VirtualMachineScaleSetVMInstanceRequiredIDs, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "subscriptionId": url.QueryEscape(client.SubscriptionID), @@ -946,7 +977,7 @@ func (client VirtualMachineScaleSetsClient) UpdateInstancesPreparer(resourceGrou "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), @@ -959,7 +990,9 @@ func (client VirtualMachineScaleSetsClient) UpdateInstancesPreparer(resourceGrou // UpdateInstancesSender sends the UpdateInstances request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetsClient) UpdateInstancesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // UpdateInstancesResponder handles the response to the UpdateInstances request. The method always @@ -968,7 +1001,7 @@ func (client VirtualMachineScaleSetsClient) UpdateInstancesResponder(resp *http. err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachinescalesetvms.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachinescalesetvms.go index ec432f64e40b..a301e8f7bb1f 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachinescalesetvms.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachinescalesetvms.go @@ -14,12 +14,13 @@ package compute // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -41,33 +42,36 @@ func NewVirtualMachineScaleSetVMsClientWithBaseURI(baseURI string, subscriptionI return VirtualMachineScaleSetVMsClient{NewWithBaseURI(baseURI, subscriptionID)} } -// Deallocate the operation to deallocate a virtual machine scale set. +// Deallocate the operation to deallocate a virtual machine scale set. This +// method may poll for completion. Polling can be canceled by passing the +// cancel channel argument. The channel will be used to cancel polling and +// any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. vmScaleSetName is the // name of the virtual machine scale set. instanceID is the instance id of // the virtual machine. -func (client VirtualMachineScaleSetVMsClient) Deallocate(resourceGroupName string, vmScaleSetName string, instanceID string) (result autorest.Response, ae error) { - req, err := client.DeallocatePreparer(resourceGroupName, vmScaleSetName, instanceID) +func (client VirtualMachineScaleSetVMsClient) Deallocate(resourceGroupName string, vmScaleSetName string, instanceID string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeallocatePreparer(resourceGroupName, vmScaleSetName, instanceID, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetVMsClient", "Deallocate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Deallocate", nil, "Failure preparing request") } resp, err := client.DeallocateSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetVMsClient", "Deallocate", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Deallocate", resp, "Failure sending request") } result, err = client.DeallocateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetVMsClient", "Deallocate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Deallocate", resp, "Failure responding to request") } return } // DeallocatePreparer prepares the Deallocate request. -func (client VirtualMachineScaleSetVMsClient) DeallocatePreparer(resourceGroupName string, vmScaleSetName string, instanceID string) (*http.Request, error) { +func (client VirtualMachineScaleSetVMsClient) DeallocatePreparer(resourceGroupName string, vmScaleSetName string, instanceID string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": url.QueryEscape(instanceID), "resourceGroupName": url.QueryEscape(resourceGroupName), @@ -79,7 +83,7 @@ func (client VirtualMachineScaleSetVMsClient) DeallocatePreparer(resourceGroupNa "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), @@ -91,7 +95,9 @@ func (client VirtualMachineScaleSetVMsClient) DeallocatePreparer(resourceGroupNa // DeallocateSender sends the Deallocate request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) DeallocateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // DeallocateResponder handles the response to the Deallocate request. The method always @@ -100,39 +106,42 @@ func (client VirtualMachineScaleSetVMsClient) DeallocateResponder(resp *http.Res err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } -// Delete the operation to delete a virtual machine scale set. +// Delete the operation to delete a virtual machine scale set. This method may +// poll for completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. // // resourceGroupName is the name of the resource group. vmScaleSetName is the // name of the virtual machine scale set. instanceID is the instance id of // the virtual machine. -func (client VirtualMachineScaleSetVMsClient) Delete(resourceGroupName string, vmScaleSetName string, instanceID string) (result autorest.Response, ae error) { - req, err := client.DeletePreparer(resourceGroupName, vmScaleSetName, instanceID) +func (client VirtualMachineScaleSetVMsClient) Delete(resourceGroupName string, vmScaleSetName string, instanceID string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, vmScaleSetName, instanceID, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetVMsClient", "Delete", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Delete", nil, "Failure preparing request") } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetVMsClient", "Delete", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Delete", resp, "Failure sending request") } result, err = client.DeleteResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetVMsClient", "Delete", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Delete", resp, "Failure responding to request") } return } // DeletePreparer prepares the Delete request. -func (client VirtualMachineScaleSetVMsClient) DeletePreparer(resourceGroupName string, vmScaleSetName string, instanceID string) (*http.Request, error) { +func (client VirtualMachineScaleSetVMsClient) DeletePreparer(resourceGroupName string, vmScaleSetName string, instanceID string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": url.QueryEscape(instanceID), "resourceGroupName": url.QueryEscape(resourceGroupName), @@ -144,7 +153,7 @@ func (client VirtualMachineScaleSetVMsClient) DeletePreparer(resourceGroupName s "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), @@ -156,7 +165,9 @@ func (client VirtualMachineScaleSetVMsClient) DeletePreparer(resourceGroupName s // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusNoContent, http.StatusAccepted) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // DeleteResponder handles the response to the Delete request. The method always @@ -165,7 +176,7 @@ func (client VirtualMachineScaleSetVMsClient) DeleteResponder(resp *http.Respons err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent, http.StatusAccepted), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return @@ -176,21 +187,21 @@ func (client VirtualMachineScaleSetVMsClient) DeleteResponder(resp *http.Respons // resourceGroupName is the name of the resource group. vmScaleSetName is the // name of the virtual machine scale set. instanceID is the instance id of // the virtual machine. -func (client VirtualMachineScaleSetVMsClient) Get(resourceGroupName string, vmScaleSetName string, instanceID string) (result VirtualMachineScaleSetVM, ae error) { +func (client VirtualMachineScaleSetVMsClient) Get(resourceGroupName string, vmScaleSetName string, instanceID string) (result VirtualMachineScaleSetVM, err error) { req, err := client.GetPreparer(resourceGroupName, vmScaleSetName, instanceID) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetVMsClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetVMsClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetVMsClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Get", resp, "Failure responding to request") } return @@ -221,7 +232,7 @@ func (client VirtualMachineScaleSetVMsClient) GetPreparer(resourceGroupName stri // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -230,7 +241,7 @@ func (client VirtualMachineScaleSetVMsClient) GetResponder(resp *http.Response) err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -243,21 +254,21 @@ func (client VirtualMachineScaleSetVMsClient) GetResponder(resp *http.Response) // resourceGroupName is the name of the resource group. vmScaleSetName is the // name of the virtual machine scale set. instanceID is the instance id of // the virtual machine. -func (client VirtualMachineScaleSetVMsClient) GetInstanceView(resourceGroupName string, vmScaleSetName string, instanceID string) (result VirtualMachineScaleSetVMInstanceView, ae error) { +func (client VirtualMachineScaleSetVMsClient) GetInstanceView(resourceGroupName string, vmScaleSetName string, instanceID string) (result VirtualMachineScaleSetVMInstanceView, err error) { req, err := client.GetInstanceViewPreparer(resourceGroupName, vmScaleSetName, instanceID) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetVMsClient", "GetInstanceView", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "GetInstanceView", nil, "Failure preparing request") } resp, err := client.GetInstanceViewSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetVMsClient", "GetInstanceView", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "GetInstanceView", resp, "Failure sending request") } result, err = client.GetInstanceViewResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetVMsClient", "GetInstanceView", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "GetInstanceView", resp, "Failure responding to request") } return @@ -288,7 +299,7 @@ func (client VirtualMachineScaleSetVMsClient) GetInstanceViewPreparer(resourceGr // GetInstanceViewSender sends the GetInstanceView request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) GetInstanceViewSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetInstanceViewResponder handles the response to the GetInstanceView request. The method always @@ -297,7 +308,7 @@ func (client VirtualMachineScaleSetVMsClient) GetInstanceViewResponder(resp *htt err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -311,21 +322,21 @@ func (client VirtualMachineScaleSetVMsClient) GetInstanceViewResponder(resp *htt // filter is the filter to apply on the operation. selectParameter is the // list parameters. expand is the expand expression to apply on the // operation. -func (client VirtualMachineScaleSetVMsClient) List(resourceGroupName string, virtualMachineScaleSetName string, filter string, selectParameter string, expand string) (result VirtualMachineScaleSetVMListResult, ae error) { +func (client VirtualMachineScaleSetVMsClient) List(resourceGroupName string, virtualMachineScaleSetName string, filter string, selectParameter string, expand string) (result VirtualMachineScaleSetVMListResult, err error) { req, err := client.ListPreparer(resourceGroupName, virtualMachineScaleSetName, filter, selectParameter, expand) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetVMsClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetVMsClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetVMsClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "List", resp, "Failure responding to request") } return @@ -364,7 +375,7 @@ func (client VirtualMachineScaleSetVMsClient) ListPreparer(resourceGroupName str // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -373,7 +384,7 @@ func (client VirtualMachineScaleSetVMsClient) ListResponder(resp *http.Response) err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -381,10 +392,10 @@ func (client VirtualMachineScaleSetVMsClient) ListResponder(resp *http.Response) } // ListNextResults retrieves the next set of results, if any. -func (client VirtualMachineScaleSetVMsClient) ListNextResults(lastResults VirtualMachineScaleSetVMListResult) (result VirtualMachineScaleSetVMListResult, ae error) { +func (client VirtualMachineScaleSetVMsClient) ListNextResults(lastResults VirtualMachineScaleSetVMListResult) (result VirtualMachineScaleSetVMListResult, err error) { req, err := lastResults.VirtualMachineScaleSetVMListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetVMsClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -393,44 +404,47 @@ func (client VirtualMachineScaleSetVMsClient) ListNextResults(lastResults Virtua resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetVMsClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetVMsClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "List", resp, "Failure responding to next results request request") } return } // PowerOff the operation to power off (stop) a virtual machine scale set. +// This method may poll for completion. Polling can be canceled by passing +// the cancel channel argument. The channel will be used to cancel polling +// and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. vmScaleSetName is the // name of the virtual machine scale set. instanceID is the instance id of // the virtual machine. -func (client VirtualMachineScaleSetVMsClient) PowerOff(resourceGroupName string, vmScaleSetName string, instanceID string) (result autorest.Response, ae error) { - req, err := client.PowerOffPreparer(resourceGroupName, vmScaleSetName, instanceID) +func (client VirtualMachineScaleSetVMsClient) PowerOff(resourceGroupName string, vmScaleSetName string, instanceID string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.PowerOffPreparer(resourceGroupName, vmScaleSetName, instanceID, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetVMsClient", "PowerOff", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "PowerOff", nil, "Failure preparing request") } resp, err := client.PowerOffSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetVMsClient", "PowerOff", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "PowerOff", resp, "Failure sending request") } result, err = client.PowerOffResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetVMsClient", "PowerOff", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "PowerOff", resp, "Failure responding to request") } return } // PowerOffPreparer prepares the PowerOff request. -func (client VirtualMachineScaleSetVMsClient) PowerOffPreparer(resourceGroupName string, vmScaleSetName string, instanceID string) (*http.Request, error) { +func (client VirtualMachineScaleSetVMsClient) PowerOffPreparer(resourceGroupName string, vmScaleSetName string, instanceID string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": url.QueryEscape(instanceID), "resourceGroupName": url.QueryEscape(resourceGroupName), @@ -442,7 +456,7 @@ func (client VirtualMachineScaleSetVMsClient) PowerOffPreparer(resourceGroupName "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), @@ -454,7 +468,9 @@ func (client VirtualMachineScaleSetVMsClient) PowerOffPreparer(resourceGroupName // PowerOffSender sends the PowerOff request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) PowerOffSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // PowerOffResponder handles the response to the PowerOff request. The method always @@ -463,39 +479,42 @@ func (client VirtualMachineScaleSetVMsClient) PowerOffResponder(resp *http.Respo err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } -// Restart the operation to restart a virtual machine scale set. +// Restart the operation to restart a virtual machine scale set. This method +// may poll for completion. Polling can be canceled by passing the cancel +// channel argument. The channel will be used to cancel polling and any +// outstanding HTTP requests. // // resourceGroupName is the name of the resource group. vmScaleSetName is the // name of the virtual machine scale set. instanceID is the instance id of // the virtual machine. -func (client VirtualMachineScaleSetVMsClient) Restart(resourceGroupName string, vmScaleSetName string, instanceID string) (result autorest.Response, ae error) { - req, err := client.RestartPreparer(resourceGroupName, vmScaleSetName, instanceID) +func (client VirtualMachineScaleSetVMsClient) Restart(resourceGroupName string, vmScaleSetName string, instanceID string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.RestartPreparer(resourceGroupName, vmScaleSetName, instanceID, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetVMsClient", "Restart", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Restart", nil, "Failure preparing request") } resp, err := client.RestartSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetVMsClient", "Restart", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Restart", resp, "Failure sending request") } result, err = client.RestartResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetVMsClient", "Restart", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Restart", resp, "Failure responding to request") } return } // RestartPreparer prepares the Restart request. -func (client VirtualMachineScaleSetVMsClient) RestartPreparer(resourceGroupName string, vmScaleSetName string, instanceID string) (*http.Request, error) { +func (client VirtualMachineScaleSetVMsClient) RestartPreparer(resourceGroupName string, vmScaleSetName string, instanceID string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": url.QueryEscape(instanceID), "resourceGroupName": url.QueryEscape(resourceGroupName), @@ -507,7 +526,7 @@ func (client VirtualMachineScaleSetVMsClient) RestartPreparer(resourceGroupName "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), @@ -519,7 +538,9 @@ func (client VirtualMachineScaleSetVMsClient) RestartPreparer(resourceGroupName // RestartSender sends the Restart request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) RestartSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // RestartResponder handles the response to the Restart request. The method always @@ -528,39 +549,42 @@ func (client VirtualMachineScaleSetVMsClient) RestartResponder(resp *http.Respon err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } -// Start the operation to start a virtual machine scale set. +// Start the operation to start a virtual machine scale set. This method may +// poll for completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. // // resourceGroupName is the name of the resource group. vmScaleSetName is the // name of the virtual machine scale set. instanceID is the instance id of // the virtual machine. -func (client VirtualMachineScaleSetVMsClient) Start(resourceGroupName string, vmScaleSetName string, instanceID string) (result autorest.Response, ae error) { - req, err := client.StartPreparer(resourceGroupName, vmScaleSetName, instanceID) +func (client VirtualMachineScaleSetVMsClient) Start(resourceGroupName string, vmScaleSetName string, instanceID string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.StartPreparer(resourceGroupName, vmScaleSetName, instanceID, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetVMsClient", "Start", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Start", nil, "Failure preparing request") } resp, err := client.StartSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetVMsClient", "Start", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Start", resp, "Failure sending request") } result, err = client.StartResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineScaleSetVMsClient", "Start", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Start", resp, "Failure responding to request") } return } // StartPreparer prepares the Start request. -func (client VirtualMachineScaleSetVMsClient) StartPreparer(resourceGroupName string, vmScaleSetName string, instanceID string) (*http.Request, error) { +func (client VirtualMachineScaleSetVMsClient) StartPreparer(resourceGroupName string, vmScaleSetName string, instanceID string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": url.QueryEscape(instanceID), "resourceGroupName": url.QueryEscape(resourceGroupName), @@ -572,7 +596,7 @@ func (client VirtualMachineScaleSetVMsClient) StartPreparer(resourceGroupName st "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), @@ -584,7 +608,9 @@ func (client VirtualMachineScaleSetVMsClient) StartPreparer(resourceGroupName st // StartSender sends the Start request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineScaleSetVMsClient) StartSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // StartResponder handles the response to the Start request. The method always @@ -593,7 +619,7 @@ func (client VirtualMachineScaleSetVMsClient) StartResponder(resp *http.Response err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachinesizes.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachinesizes.go index dca91c6fb46c..cccba5308bd3 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachinesizes.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/virtualmachinesizes.go @@ -14,12 +14,13 @@ package compute // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -44,21 +45,21 @@ func NewVirtualMachineSizesClientWithBaseURI(baseURI string, subscriptionID stri // List lists virtual-machine-sizes available in a location for a subscription. // // location is the location upon which virtual-machine-sizes is queried. -func (client VirtualMachineSizesClient) List(location string) (result VirtualMachineSizeListResult, ae error) { +func (client VirtualMachineSizesClient) List(location string) (result VirtualMachineSizeListResult, err error) { req, err := client.ListPreparer(location) if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineSizesClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineSizesClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineSizesClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineSizesClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineSizesClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineSizesClient", "List", resp, "Failure responding to request") } return @@ -87,7 +88,7 @@ func (client VirtualMachineSizesClient) ListPreparer(location string) (*http.Req // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client VirtualMachineSizesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -96,7 +97,7 @@ func (client VirtualMachineSizesClient) ListResponder(resp *http.Response) (resu err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -104,10 +105,10 @@ func (client VirtualMachineSizesClient) ListResponder(resp *http.Response) (resu } // ListNextResults retrieves the next set of results, if any. -func (client VirtualMachineSizesClient) ListNextResults(lastResults VirtualMachineSizeListResult) (result VirtualMachineSizeListResult, ae error) { +func (client VirtualMachineSizesClient) ListNextResults(lastResults VirtualMachineSizeListResult) (result VirtualMachineSizeListResult, err error) { req, err := lastResults.VirtualMachineSizeListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineSizesClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineSizesClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -116,12 +117,12 @@ func (client VirtualMachineSizesClient) ListNextResults(lastResults VirtualMachi resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute/VirtualMachineSizesClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "compute.VirtualMachineSizesClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "compute/VirtualMachineSizesClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineSizesClient", "List", resp, "Failure responding to next results request request") } return diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/applicationgateways.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/applicationgateways.go index 40adba140812..92d40233c1be 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/applicationgateways.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/applicationgateways.go @@ -14,12 +14,13 @@ package network // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -46,33 +47,35 @@ func NewApplicationGatewaysClientWithBaseURI(baseURI string, subscriptionID stri } // CreateOrUpdate the Put ApplicationGateway operation creates/updates a -// ApplicationGateway +// ApplicationGateway This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. applicationGatewayName // is the name of the ApplicationGateway. parameters is parameters supplied // to the create/delete ApplicationGateway operation -func (client ApplicationGatewaysClient) CreateOrUpdate(resourceGroupName string, applicationGatewayName string, parameters ApplicationGateway) (result ApplicationGateway, ae error) { - req, err := client.CreateOrUpdatePreparer(resourceGroupName, applicationGatewayName, parameters) +func (client ApplicationGatewaysClient) CreateOrUpdate(resourceGroupName string, applicationGatewayName string, parameters ApplicationGateway, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, applicationGatewayName, parameters, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/ApplicationGatewaysClient", "CreateOrUpdate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "CreateOrUpdate", nil, "Failure preparing request") } resp, err := client.CreateOrUpdateSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/ApplicationGatewaysClient", "CreateOrUpdate", resp.StatusCode, "Failure sending request") + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "CreateOrUpdate", resp, "Failure sending request") } result, err = client.CreateOrUpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ApplicationGatewaysClient", "CreateOrUpdate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "CreateOrUpdate", resp, "Failure responding to request") } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ApplicationGatewaysClient) CreateOrUpdatePreparer(resourceGroupName string, applicationGatewayName string, parameters ApplicationGateway) (*http.Request, error) { +func (client ApplicationGatewaysClient) CreateOrUpdatePreparer(resourceGroupName string, applicationGatewayName string, parameters ApplicationGateway, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "applicationGatewayName": url.QueryEscape(applicationGatewayName), "resourceGroupName": url.QueryEscape(resourceGroupName), @@ -83,7 +86,7 @@ func (client ApplicationGatewaysClient) CreateOrUpdatePreparer(resourceGroupName "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), @@ -96,49 +99,52 @@ func (client ApplicationGatewaysClient) CreateOrUpdatePreparer(resourceGroupName // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client ApplicationGatewaysClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusCreated, http.StatusOK) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client ApplicationGatewaysClient) CreateOrUpdateResponder(resp *http.Response) (result ApplicationGateway, err error) { +func (client ApplicationGatewaysClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), - autorest.ByUnmarshallingJSON(&result), + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + result.Response = resp return } // Delete the delete applicationgateway operation deletes the specified -// applicationgateway. +// applicationgateway. This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. applicationGatewayName // is the name of the applicationgateway. -func (client ApplicationGatewaysClient) Delete(resourceGroupName string, applicationGatewayName string) (result autorest.Response, ae error) { - req, err := client.DeletePreparer(resourceGroupName, applicationGatewayName) +func (client ApplicationGatewaysClient) Delete(resourceGroupName string, applicationGatewayName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, applicationGatewayName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/ApplicationGatewaysClient", "Delete", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Delete", nil, "Failure preparing request") } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "network/ApplicationGatewaysClient", "Delete", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Delete", resp, "Failure sending request") } result, err = client.DeleteResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ApplicationGatewaysClient", "Delete", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Delete", resp, "Failure responding to request") } return } // DeletePreparer prepares the Delete request. -func (client ApplicationGatewaysClient) DeletePreparer(resourceGroupName string, applicationGatewayName string) (*http.Request, error) { +func (client ApplicationGatewaysClient) DeletePreparer(resourceGroupName string, applicationGatewayName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "applicationGatewayName": url.QueryEscape(applicationGatewayName), "resourceGroupName": url.QueryEscape(resourceGroupName), @@ -149,7 +155,7 @@ func (client ApplicationGatewaysClient) DeletePreparer(resourceGroupName string, "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), @@ -161,7 +167,9 @@ func (client ApplicationGatewaysClient) DeletePreparer(resourceGroupName string, // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client ApplicationGatewaysClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusAccepted, http.StatusNoContent, http.StatusOK) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // DeleteResponder handles the response to the Delete request. The method always @@ -170,7 +178,7 @@ func (client ApplicationGatewaysClient) DeleteResponder(resp *http.Response) (re err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusNoContent, http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusNoContent, http.StatusOK), autorest.ByClosing()) result.Response = resp return @@ -181,21 +189,21 @@ func (client ApplicationGatewaysClient) DeleteResponder(resp *http.Response) (re // // resourceGroupName is the name of the resource group. applicationGatewayName // is the name of the applicationgateway. -func (client ApplicationGatewaysClient) Get(resourceGroupName string, applicationGatewayName string) (result ApplicationGateway, ae error) { +func (client ApplicationGatewaysClient) Get(resourceGroupName string, applicationGatewayName string) (result ApplicationGateway, err error) { req, err := client.GetPreparer(resourceGroupName, applicationGatewayName) if err != nil { - return result, autorest.NewErrorWithError(err, "network/ApplicationGatewaysClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/ApplicationGatewaysClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ApplicationGatewaysClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Get", resp, "Failure responding to request") } return @@ -225,7 +233,7 @@ func (client ApplicationGatewaysClient) GetPreparer(resourceGroupName string, ap // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client ApplicationGatewaysClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -234,7 +242,7 @@ func (client ApplicationGatewaysClient) GetResponder(resp *http.Response) (resul err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -245,21 +253,21 @@ func (client ApplicationGatewaysClient) GetResponder(resp *http.Response) (resul // applicationgateways in a resource group. // // resourceGroupName is the name of the resource group. -func (client ApplicationGatewaysClient) List(resourceGroupName string) (result ApplicationGatewayListResult, ae error) { +func (client ApplicationGatewaysClient) List(resourceGroupName string) (result ApplicationGatewayListResult, err error) { req, err := client.ListPreparer(resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "network/ApplicationGatewaysClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/ApplicationGatewaysClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ApplicationGatewaysClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "List", resp, "Failure responding to request") } return @@ -288,7 +296,7 @@ func (client ApplicationGatewaysClient) ListPreparer(resourceGroupName string) ( // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client ApplicationGatewaysClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -297,7 +305,7 @@ func (client ApplicationGatewaysClient) ListResponder(resp *http.Response) (resu err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -305,10 +313,10 @@ func (client ApplicationGatewaysClient) ListResponder(resp *http.Response) (resu } // ListNextResults retrieves the next set of results, if any. -func (client ApplicationGatewaysClient) ListNextResults(lastResults ApplicationGatewayListResult) (result ApplicationGatewayListResult, ae error) { +func (client ApplicationGatewaysClient) ListNextResults(lastResults ApplicationGatewayListResult) (result ApplicationGatewayListResult, err error) { req, err := lastResults.ApplicationGatewayListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/ApplicationGatewaysClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -317,12 +325,12 @@ func (client ApplicationGatewaysClient) ListNextResults(lastResults ApplicationG resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/ApplicationGatewaysClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ApplicationGatewaysClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "List", resp, "Failure responding to next results request request") } return @@ -330,21 +338,21 @@ func (client ApplicationGatewaysClient) ListNextResults(lastResults ApplicationG // ListAll the List applicationgateway opertion retrieves all the // applicationgateways in a subscription. -func (client ApplicationGatewaysClient) ListAll() (result ApplicationGatewayListResult, ae error) { +func (client ApplicationGatewaysClient) ListAll() (result ApplicationGatewayListResult, err error) { req, err := client.ListAllPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/ApplicationGatewaysClient", "ListAll", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAll", nil, "Failure preparing request") } resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/ApplicationGatewaysClient", "ListAll", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAll", resp, "Failure sending request") } result, err = client.ListAllResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ApplicationGatewaysClient", "ListAll", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAll", resp, "Failure responding to request") } return @@ -372,7 +380,7 @@ func (client ApplicationGatewaysClient) ListAllPreparer() (*http.Request, error) // ListAllSender sends the ListAll request. The method will close the // http.Response Body if it receives an error. func (client ApplicationGatewaysClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListAllResponder handles the response to the ListAll request. The method always @@ -381,7 +389,7 @@ func (client ApplicationGatewaysClient) ListAllResponder(resp *http.Response) (r err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -389,10 +397,10 @@ func (client ApplicationGatewaysClient) ListAllResponder(resp *http.Response) (r } // ListAllNextResults retrieves the next set of results, if any. -func (client ApplicationGatewaysClient) ListAllNextResults(lastResults ApplicationGatewayListResult) (result ApplicationGatewayListResult, ae error) { +func (client ApplicationGatewaysClient) ListAllNextResults(lastResults ApplicationGatewayListResult) (result ApplicationGatewayListResult, err error) { req, err := lastResults.ApplicationGatewayListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/ApplicationGatewaysClient", "ListAll", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAll", nil, "Failure preparing next results request request") } if req == nil { return @@ -401,44 +409,47 @@ func (client ApplicationGatewaysClient) ListAllNextResults(lastResults Applicati resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/ApplicationGatewaysClient", "ListAll", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAll", resp, "Failure sending next results request request") } result, err = client.ListAllResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ApplicationGatewaysClient", "ListAll", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAll", resp, "Failure responding to next results request request") } return } // Start the Start ApplicationGateway operation starts application gatewayin -// the specified resource group through Network resource provider. +// the specified resource group through Network resource provider. This +// method may poll for completion. Polling can be canceled by passing the +// cancel channel argument. The channel will be used to cancel polling and +// any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. applicationGatewayName // is the name of the application gateway. -func (client ApplicationGatewaysClient) Start(resourceGroupName string, applicationGatewayName string) (result autorest.Response, ae error) { - req, err := client.StartPreparer(resourceGroupName, applicationGatewayName) +func (client ApplicationGatewaysClient) Start(resourceGroupName string, applicationGatewayName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.StartPreparer(resourceGroupName, applicationGatewayName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/ApplicationGatewaysClient", "Start", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Start", nil, "Failure preparing request") } resp, err := client.StartSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "network/ApplicationGatewaysClient", "Start", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Start", resp, "Failure sending request") } result, err = client.StartResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ApplicationGatewaysClient", "Start", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Start", resp, "Failure responding to request") } return } // StartPreparer prepares the Start request. -func (client ApplicationGatewaysClient) StartPreparer(resourceGroupName string, applicationGatewayName string) (*http.Request, error) { +func (client ApplicationGatewaysClient) StartPreparer(resourceGroupName string, applicationGatewayName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "applicationGatewayName": url.QueryEscape(applicationGatewayName), "resourceGroupName": url.QueryEscape(resourceGroupName), @@ -449,7 +460,7 @@ func (client ApplicationGatewaysClient) StartPreparer(resourceGroupName string, "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), @@ -461,7 +472,9 @@ func (client ApplicationGatewaysClient) StartPreparer(resourceGroupName string, // StartSender sends the Start request. The method will close the // http.Response Body if it receives an error. func (client ApplicationGatewaysClient) StartSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // StartResponder handles the response to the Start request. The method always @@ -470,39 +483,42 @@ func (client ApplicationGatewaysClient) StartResponder(resp *http.Response) (res err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } // Stop the STOP ApplicationGateway operation stops application gatewayin the -// specified resource group through Network resource provider. +// specified resource group through Network resource provider. This method +// may poll for completion. Polling can be canceled by passing the cancel +// channel argument. The channel will be used to cancel polling and any +// outstanding HTTP requests. // // resourceGroupName is the name of the resource group. applicationGatewayName // is the name of the application gateway. -func (client ApplicationGatewaysClient) Stop(resourceGroupName string, applicationGatewayName string) (result autorest.Response, ae error) { - req, err := client.StopPreparer(resourceGroupName, applicationGatewayName) +func (client ApplicationGatewaysClient) Stop(resourceGroupName string, applicationGatewayName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.StopPreparer(resourceGroupName, applicationGatewayName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/ApplicationGatewaysClient", "Stop", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Stop", nil, "Failure preparing request") } resp, err := client.StopSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "network/ApplicationGatewaysClient", "Stop", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Stop", resp, "Failure sending request") } result, err = client.StopResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ApplicationGatewaysClient", "Stop", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Stop", resp, "Failure responding to request") } return } // StopPreparer prepares the Stop request. -func (client ApplicationGatewaysClient) StopPreparer(resourceGroupName string, applicationGatewayName string) (*http.Request, error) { +func (client ApplicationGatewaysClient) StopPreparer(resourceGroupName string, applicationGatewayName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "applicationGatewayName": url.QueryEscape(applicationGatewayName), "resourceGroupName": url.QueryEscape(resourceGroupName), @@ -513,7 +529,7 @@ func (client ApplicationGatewaysClient) StopPreparer(resourceGroupName string, a "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), @@ -525,7 +541,9 @@ func (client ApplicationGatewaysClient) StopPreparer(resourceGroupName string, a // StopSender sends the Stop request. The method will close the // http.Response Body if it receives an error. func (client ApplicationGatewaysClient) StopSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // StopResponder handles the response to the Stop request. The method always @@ -534,7 +552,7 @@ func (client ApplicationGatewaysClient) StopResponder(resp *http.Response) (resu err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/client.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/client.go index 542b007579ea..ba6a2dace79f 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/client.go @@ -1,3 +1,10 @@ +// Package network implements the Azure ARM Network service API version +// 2015-06-15. +// +// The Microsoft Azure Network management API provides a RESTful set of web +// services that interact with Microsoft Azure Networks service to manage +// your network resrources. The API has entities that capture the +// relationship between an end user and the Microsoft Azure Networks service. package network // Copyright (c) Microsoft and contributors. All rights reserved. @@ -14,12 +21,13 @@ package network // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -32,11 +40,7 @@ const ( DefaultBaseURI = "https://management.azure.com" ) -// ManagementClient is the the Microsoft Azure Network management API provides -// a RESTful set of web services that interact with Microsoft Azure Networks -// service to manage your network resrources. The API has entities that -// capture the relationship between an end user and the Microsoft Azure -// Networks service. +// ManagementClient is the base client for Network. type ManagementClient struct { autorest.Client BaseURI string @@ -63,21 +67,21 @@ func NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient { // location is the location of the domain name domainNameLabel is the domain // name to be verified. It must conform to the following regular expression: // ^[a-z][a-z0-9-]{1,61}[a-z0-9]$. -func (client ManagementClient) CheckDNSNameAvailability(location string, domainNameLabel string) (result DNSNameAvailabilityResult, ae error) { +func (client ManagementClient) CheckDNSNameAvailability(location string, domainNameLabel string) (result DNSNameAvailabilityResult, err error) { req, err := client.CheckDNSNameAvailabilityPreparer(location, domainNameLabel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/ManagementClient", "CheckDNSNameAvailability", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.ManagementClient", "CheckDNSNameAvailability", nil, "Failure preparing request") } resp, err := client.CheckDNSNameAvailabilitySender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/ManagementClient", "CheckDNSNameAvailability", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.ManagementClient", "CheckDNSNameAvailability", resp, "Failure sending request") } result, err = client.CheckDNSNameAvailabilityResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ManagementClient", "CheckDNSNameAvailability", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.ManagementClient", "CheckDNSNameAvailability", resp, "Failure responding to request") } return @@ -109,7 +113,7 @@ func (client ManagementClient) CheckDNSNameAvailabilityPreparer(location string, // CheckDNSNameAvailabilitySender sends the CheckDNSNameAvailability request. The method will close the // http.Response Body if it receives an error. func (client ManagementClient) CheckDNSNameAvailabilitySender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // CheckDNSNameAvailabilityResponder handles the response to the CheckDNSNameAvailability request. The method always @@ -118,7 +122,7 @@ func (client ManagementClient) CheckDNSNameAvailabilityResponder(resp *http.Resp err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/expressroutecircuitauthorizations.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/expressroutecircuitauthorizations.go index a5ac72e678a4..9d425553938a 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/expressroutecircuitauthorizations.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/expressroutecircuitauthorizations.go @@ -14,12 +14,13 @@ package network // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -46,34 +47,37 @@ func NewExpressRouteCircuitAuthorizationsClientWithBaseURI(baseURI string, subsc } // CreateOrUpdate the Put Authorization operation creates/updates an -// authorization in thespecified ExpressRouteCircuits +// authorization in thespecified ExpressRouteCircuits This method may poll +// for completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. // // resourceGroupName is the name of the resource group. circuitName is the // name of the express route circuit. authorizationName is the name of the // authorization. authorizationParameters is parameters supplied to the // create/update ExpressRouteCircuitAuthorization operation -func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdate(resourceGroupName string, circuitName string, authorizationName string, authorizationParameters ExpressRouteCircuitAuthorization) (result ExpressRouteCircuitAuthorization, ae error) { - req, err := client.CreateOrUpdatePreparer(resourceGroupName, circuitName, authorizationName, authorizationParameters) +func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdate(resourceGroupName string, circuitName string, authorizationName string, authorizationParameters ExpressRouteCircuitAuthorization, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, circuitName, authorizationName, authorizationParameters, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitAuthorizationsClient", "CreateOrUpdate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "CreateOrUpdate", nil, "Failure preparing request") } resp, err := client.CreateOrUpdateSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitAuthorizationsClient", "CreateOrUpdate", resp.StatusCode, "Failure sending request") + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "CreateOrUpdate", resp, "Failure sending request") } result, err = client.CreateOrUpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ExpressRouteCircuitAuthorizationsClient", "CreateOrUpdate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "CreateOrUpdate", resp, "Failure responding to request") } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdatePreparer(resourceGroupName string, circuitName string, authorizationName string, authorizationParameters ExpressRouteCircuitAuthorization) (*http.Request, error) { +func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdatePreparer(resourceGroupName string, circuitName string, authorizationName string, authorizationParameters ExpressRouteCircuitAuthorization, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "authorizationName": url.QueryEscape(authorizationName), "circuitName": url.QueryEscape(circuitName), @@ -85,7 +89,7 @@ func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdatePreparer(res "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), @@ -98,50 +102,54 @@ func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdatePreparer(res // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusCreated, http.StatusOK) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRouteCircuitAuthorization, err error) { +func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), - autorest.ByUnmarshallingJSON(&result), + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + result.Response = resp return } // Delete the delete authorization operation deletes the specified -// authorization from the specified ExpressRouteCircuit. +// authorization from the specified ExpressRouteCircuit. This method may poll +// for completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. // // resourceGroupName is the name of the resource group. circuitName is the // name of the express route circuit. authorizationName is the name of the // authorization. -func (client ExpressRouteCircuitAuthorizationsClient) Delete(resourceGroupName string, circuitName string, authorizationName string) (result autorest.Response, ae error) { - req, err := client.DeletePreparer(resourceGroupName, circuitName, authorizationName) +func (client ExpressRouteCircuitAuthorizationsClient) Delete(resourceGroupName string, circuitName string, authorizationName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, circuitName, authorizationName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitAuthorizationsClient", "Delete", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Delete", nil, "Failure preparing request") } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitAuthorizationsClient", "Delete", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Delete", resp, "Failure sending request") } result, err = client.DeleteResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ExpressRouteCircuitAuthorizationsClient", "Delete", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Delete", resp, "Failure responding to request") } return } // DeletePreparer prepares the Delete request. -func (client ExpressRouteCircuitAuthorizationsClient) DeletePreparer(resourceGroupName string, circuitName string, authorizationName string) (*http.Request, error) { +func (client ExpressRouteCircuitAuthorizationsClient) DeletePreparer(resourceGroupName string, circuitName string, authorizationName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "authorizationName": url.QueryEscape(authorizationName), "circuitName": url.QueryEscape(circuitName), @@ -153,7 +161,7 @@ func (client ExpressRouteCircuitAuthorizationsClient) DeletePreparer(resourceGro "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), @@ -165,7 +173,9 @@ func (client ExpressRouteCircuitAuthorizationsClient) DeletePreparer(resourceGro // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client ExpressRouteCircuitAuthorizationsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusAccepted, http.StatusOK, http.StatusNoContent) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // DeleteResponder handles the response to the Delete request. The method always @@ -174,7 +184,7 @@ func (client ExpressRouteCircuitAuthorizationsClient) DeleteResponder(resp *http err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusOK, http.StatusNoContent), + azure.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusOK, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return @@ -186,21 +196,21 @@ func (client ExpressRouteCircuitAuthorizationsClient) DeleteResponder(resp *http // resourceGroupName is the name of the resource group. circuitName is the // name of the express route circuit. authorizationName is the name of the // authorization. -func (client ExpressRouteCircuitAuthorizationsClient) Get(resourceGroupName string, circuitName string, authorizationName string) (result ExpressRouteCircuitAuthorization, ae error) { +func (client ExpressRouteCircuitAuthorizationsClient) Get(resourceGroupName string, circuitName string, authorizationName string) (result ExpressRouteCircuitAuthorization, err error) { req, err := client.GetPreparer(resourceGroupName, circuitName, authorizationName) if err != nil { - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitAuthorizationsClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitAuthorizationsClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ExpressRouteCircuitAuthorizationsClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Get", resp, "Failure responding to request") } return @@ -231,7 +241,7 @@ func (client ExpressRouteCircuitAuthorizationsClient) GetPreparer(resourceGroupN // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client ExpressRouteCircuitAuthorizationsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -240,7 +250,7 @@ func (client ExpressRouteCircuitAuthorizationsClient) GetResponder(resp *http.Re err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -252,21 +262,21 @@ func (client ExpressRouteCircuitAuthorizationsClient) GetResponder(resp *http.Re // // resourceGroupName is the name of the resource group. circuitName is the // name of the curcuit. -func (client ExpressRouteCircuitAuthorizationsClient) List(resourceGroupName string, circuitName string) (result AuthorizationListResult, ae error) { +func (client ExpressRouteCircuitAuthorizationsClient) List(resourceGroupName string, circuitName string) (result AuthorizationListResult, err error) { req, err := client.ListPreparer(resourceGroupName, circuitName) if err != nil { - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitAuthorizationsClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitAuthorizationsClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ExpressRouteCircuitAuthorizationsClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "List", resp, "Failure responding to request") } return @@ -296,7 +306,7 @@ func (client ExpressRouteCircuitAuthorizationsClient) ListPreparer(resourceGroup // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client ExpressRouteCircuitAuthorizationsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -305,7 +315,7 @@ func (client ExpressRouteCircuitAuthorizationsClient) ListResponder(resp *http.R err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -313,10 +323,10 @@ func (client ExpressRouteCircuitAuthorizationsClient) ListResponder(resp *http.R } // ListNextResults retrieves the next set of results, if any. -func (client ExpressRouteCircuitAuthorizationsClient) ListNextResults(lastResults AuthorizationListResult) (result AuthorizationListResult, ae error) { +func (client ExpressRouteCircuitAuthorizationsClient) ListNextResults(lastResults AuthorizationListResult) (result AuthorizationListResult, err error) { req, err := lastResults.AuthorizationListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitAuthorizationsClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -325,12 +335,12 @@ func (client ExpressRouteCircuitAuthorizationsClient) ListNextResults(lastResult resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitAuthorizationsClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ExpressRouteCircuitAuthorizationsClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "List", resp, "Failure responding to next results request request") } return diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/expressroutecircuitpeerings.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/expressroutecircuitpeerings.go index 5fcc143925bf..e600880843ba 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/expressroutecircuitpeerings.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/expressroutecircuitpeerings.go @@ -14,12 +14,13 @@ package network // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -46,34 +47,36 @@ func NewExpressRouteCircuitPeeringsClientWithBaseURI(baseURI string, subscriptio } // CreateOrUpdate the Put Pering operation creates/updates an peering in the -// specified ExpressRouteCircuits +// specified ExpressRouteCircuits This method may poll for completion. +// Polling can be canceled by passing the cancel channel argument. The +// channel will be used to cancel polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. circuitName is the // name of the express route circuit. peeringName is the name of the peering. // peeringParameters is parameters supplied to the create/update // ExpressRouteCircuit Peering operation -func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdate(resourceGroupName string, circuitName string, peeringName string, peeringParameters ExpressRouteCircuitPeering) (result ExpressRouteCircuitPeering, ae error) { - req, err := client.CreateOrUpdatePreparer(resourceGroupName, circuitName, peeringName, peeringParameters) +func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdate(resourceGroupName string, circuitName string, peeringName string, peeringParameters ExpressRouteCircuitPeering, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, circuitName, peeringName, peeringParameters, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitPeeringsClient", "CreateOrUpdate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "CreateOrUpdate", nil, "Failure preparing request") } resp, err := client.CreateOrUpdateSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitPeeringsClient", "CreateOrUpdate", resp.StatusCode, "Failure sending request") + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "CreateOrUpdate", resp, "Failure sending request") } result, err = client.CreateOrUpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ExpressRouteCircuitPeeringsClient", "CreateOrUpdate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "CreateOrUpdate", resp, "Failure responding to request") } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdatePreparer(resourceGroupName string, circuitName string, peeringName string, peeringParameters ExpressRouteCircuitPeering) (*http.Request, error) { +func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdatePreparer(resourceGroupName string, circuitName string, peeringName string, peeringParameters ExpressRouteCircuitPeering, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "circuitName": url.QueryEscape(circuitName), "peeringName": url.QueryEscape(peeringName), @@ -85,7 +88,7 @@ func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdatePreparer(resourceG "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), @@ -98,49 +101,52 @@ func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdatePreparer(resourceG // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusCreated) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRouteCircuitPeering, err error) { +func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + result.Response = resp return } // Delete the delete peering operation deletes the specified peering from the -// ExpressRouteCircuit. +// ExpressRouteCircuit. This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. circuitName is the // name of the express route circuit. peeringName is the name of the peering. -func (client ExpressRouteCircuitPeeringsClient) Delete(resourceGroupName string, circuitName string, peeringName string) (result autorest.Response, ae error) { - req, err := client.DeletePreparer(resourceGroupName, circuitName, peeringName) +func (client ExpressRouteCircuitPeeringsClient) Delete(resourceGroupName string, circuitName string, peeringName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, circuitName, peeringName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitPeeringsClient", "Delete", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Delete", nil, "Failure preparing request") } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitPeeringsClient", "Delete", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Delete", resp, "Failure sending request") } result, err = client.DeleteResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ExpressRouteCircuitPeeringsClient", "Delete", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Delete", resp, "Failure responding to request") } return } // DeletePreparer prepares the Delete request. -func (client ExpressRouteCircuitPeeringsClient) DeletePreparer(resourceGroupName string, circuitName string, peeringName string) (*http.Request, error) { +func (client ExpressRouteCircuitPeeringsClient) DeletePreparer(resourceGroupName string, circuitName string, peeringName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "circuitName": url.QueryEscape(circuitName), "peeringName": url.QueryEscape(peeringName), @@ -152,7 +158,7 @@ func (client ExpressRouteCircuitPeeringsClient) DeletePreparer(resourceGroupName "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), @@ -164,7 +170,9 @@ func (client ExpressRouteCircuitPeeringsClient) DeletePreparer(resourceGroupName // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client ExpressRouteCircuitPeeringsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted, http.StatusNoContent) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // DeleteResponder handles the response to the Delete request. The method always @@ -173,7 +181,7 @@ func (client ExpressRouteCircuitPeeringsClient) DeleteResponder(resp *http.Respo err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return @@ -184,21 +192,21 @@ func (client ExpressRouteCircuitPeeringsClient) DeleteResponder(resp *http.Respo // // resourceGroupName is the name of the resource group. circuitName is the // name of the express route circuit. peeringName is the name of the peering. -func (client ExpressRouteCircuitPeeringsClient) Get(resourceGroupName string, circuitName string, peeringName string) (result ExpressRouteCircuitPeering, ae error) { +func (client ExpressRouteCircuitPeeringsClient) Get(resourceGroupName string, circuitName string, peeringName string) (result ExpressRouteCircuitPeering, err error) { req, err := client.GetPreparer(resourceGroupName, circuitName, peeringName) if err != nil { - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitPeeringsClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitPeeringsClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ExpressRouteCircuitPeeringsClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Get", resp, "Failure responding to request") } return @@ -229,7 +237,7 @@ func (client ExpressRouteCircuitPeeringsClient) GetPreparer(resourceGroupName st // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client ExpressRouteCircuitPeeringsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -238,7 +246,7 @@ func (client ExpressRouteCircuitPeeringsClient) GetResponder(resp *http.Response err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -250,21 +258,21 @@ func (client ExpressRouteCircuitPeeringsClient) GetResponder(resp *http.Response // // resourceGroupName is the name of the resource group. circuitName is the // name of the curcuit. -func (client ExpressRouteCircuitPeeringsClient) List(resourceGroupName string, circuitName string) (result ExpressRouteCircuitPeeringListResult, ae error) { +func (client ExpressRouteCircuitPeeringsClient) List(resourceGroupName string, circuitName string) (result ExpressRouteCircuitPeeringListResult, err error) { req, err := client.ListPreparer(resourceGroupName, circuitName) if err != nil { - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitPeeringsClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitPeeringsClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ExpressRouteCircuitPeeringsClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", resp, "Failure responding to request") } return @@ -294,7 +302,7 @@ func (client ExpressRouteCircuitPeeringsClient) ListPreparer(resourceGroupName s // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client ExpressRouteCircuitPeeringsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -303,7 +311,7 @@ func (client ExpressRouteCircuitPeeringsClient) ListResponder(resp *http.Respons err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -311,10 +319,10 @@ func (client ExpressRouteCircuitPeeringsClient) ListResponder(resp *http.Respons } // ListNextResults retrieves the next set of results, if any. -func (client ExpressRouteCircuitPeeringsClient) ListNextResults(lastResults ExpressRouteCircuitPeeringListResult) (result ExpressRouteCircuitPeeringListResult, ae error) { +func (client ExpressRouteCircuitPeeringsClient) ListNextResults(lastResults ExpressRouteCircuitPeeringListResult) (result ExpressRouteCircuitPeeringListResult, err error) { req, err := lastResults.ExpressRouteCircuitPeeringListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitPeeringsClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -323,12 +331,12 @@ func (client ExpressRouteCircuitPeeringsClient) ListNextResults(lastResults Expr resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitPeeringsClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ExpressRouteCircuitPeeringsClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", resp, "Failure responding to next results request request") } return diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/expressroutecircuits.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/expressroutecircuits.go index 8b1ad1fee812..e896827ccffe 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/expressroutecircuits.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/expressroutecircuits.go @@ -14,12 +14,13 @@ package network // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -46,33 +47,35 @@ func NewExpressRouteCircuitsClientWithBaseURI(baseURI string, subscriptionID str } // CreateOrUpdate the Put ExpressRouteCircuit operation creates/updates a -// ExpressRouteCircuit +// ExpressRouteCircuit This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. circuitName is the // name of the circuit. parameters is parameters supplied to the // create/delete ExpressRouteCircuit operation -func (client ExpressRouteCircuitsClient) CreateOrUpdate(resourceGroupName string, circuitName string, parameters ExpressRouteCircuit) (result ExpressRouteCircuit, ae error) { - req, err := client.CreateOrUpdatePreparer(resourceGroupName, circuitName, parameters) +func (client ExpressRouteCircuitsClient) CreateOrUpdate(resourceGroupName string, circuitName string, parameters ExpressRouteCircuit, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, circuitName, parameters, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "CreateOrUpdate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "CreateOrUpdate", nil, "Failure preparing request") } resp, err := client.CreateOrUpdateSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "CreateOrUpdate", resp.StatusCode, "Failure sending request") + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "CreateOrUpdate", resp, "Failure sending request") } result, err = client.CreateOrUpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "CreateOrUpdate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "CreateOrUpdate", resp, "Failure responding to request") } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ExpressRouteCircuitsClient) CreateOrUpdatePreparer(resourceGroupName string, circuitName string, parameters ExpressRouteCircuit) (*http.Request, error) { +func (client ExpressRouteCircuitsClient) CreateOrUpdatePreparer(resourceGroupName string, circuitName string, parameters ExpressRouteCircuit, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "circuitName": url.QueryEscape(circuitName), "resourceGroupName": url.QueryEscape(resourceGroupName), @@ -83,7 +86,7 @@ func (client ExpressRouteCircuitsClient) CreateOrUpdatePreparer(resourceGroupNam "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), @@ -96,49 +99,52 @@ func (client ExpressRouteCircuitsClient) CreateOrUpdatePreparer(resourceGroupNam // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client ExpressRouteCircuitsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusCreated, http.StatusOK) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client ExpressRouteCircuitsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRouteCircuit, err error) { +func (client ExpressRouteCircuitsClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), - autorest.ByUnmarshallingJSON(&result), + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + result.Response = resp return } // Delete the delete ExpressRouteCircuit operation deletes the specified -// ExpressRouteCircuit. +// ExpressRouteCircuit. This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. circuitName is the // name of the express route Circuit. -func (client ExpressRouteCircuitsClient) Delete(resourceGroupName string, circuitName string) (result autorest.Response, ae error) { - req, err := client.DeletePreparer(resourceGroupName, circuitName) +func (client ExpressRouteCircuitsClient) Delete(resourceGroupName string, circuitName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, circuitName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "Delete", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Delete", nil, "Failure preparing request") } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "Delete", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Delete", resp, "Failure sending request") } result, err = client.DeleteResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "Delete", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Delete", resp, "Failure responding to request") } return } // DeletePreparer prepares the Delete request. -func (client ExpressRouteCircuitsClient) DeletePreparer(resourceGroupName string, circuitName string) (*http.Request, error) { +func (client ExpressRouteCircuitsClient) DeletePreparer(resourceGroupName string, circuitName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "circuitName": url.QueryEscape(circuitName), "resourceGroupName": url.QueryEscape(resourceGroupName), @@ -149,7 +155,7 @@ func (client ExpressRouteCircuitsClient) DeletePreparer(resourceGroupName string "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), @@ -161,7 +167,9 @@ func (client ExpressRouteCircuitsClient) DeletePreparer(resourceGroupName string // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client ExpressRouteCircuitsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusNoContent, http.StatusAccepted, http.StatusOK) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // DeleteResponder handles the response to the Delete request. The method always @@ -170,7 +178,7 @@ func (client ExpressRouteCircuitsClient) DeleteResponder(resp *http.Response) (r err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusAccepted, http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusAccepted, http.StatusOK), autorest.ByClosing()) result.Response = resp return @@ -181,21 +189,21 @@ func (client ExpressRouteCircuitsClient) DeleteResponder(resp *http.Response) (r // // resourceGroupName is the name of the resource group. circuitName is the // name of the circuit. -func (client ExpressRouteCircuitsClient) Get(resourceGroupName string, circuitName string) (result ExpressRouteCircuit, ae error) { +func (client ExpressRouteCircuitsClient) Get(resourceGroupName string, circuitName string) (result ExpressRouteCircuit, err error) { req, err := client.GetPreparer(resourceGroupName, circuitName) if err != nil { - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Get", resp, "Failure responding to request") } return @@ -225,7 +233,7 @@ func (client ExpressRouteCircuitsClient) GetPreparer(resourceGroupName string, c // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client ExpressRouteCircuitsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -234,7 +242,7 @@ func (client ExpressRouteCircuitsClient) GetResponder(resp *http.Response) (resu err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -245,21 +253,21 @@ func (client ExpressRouteCircuitsClient) GetResponder(resp *http.Response) (resu // ExpressRouteCircuits in a resource group. // // resourceGroupName is the name of the resource group. -func (client ExpressRouteCircuitsClient) List(resourceGroupName string) (result ExpressRouteCircuitListResult, ae error) { +func (client ExpressRouteCircuitsClient) List(resourceGroupName string) (result ExpressRouteCircuitListResult, err error) { req, err := client.ListPreparer(resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "List", resp, "Failure responding to request") } return @@ -288,7 +296,7 @@ func (client ExpressRouteCircuitsClient) ListPreparer(resourceGroupName string) // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client ExpressRouteCircuitsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -297,7 +305,7 @@ func (client ExpressRouteCircuitsClient) ListResponder(resp *http.Response) (res err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -305,10 +313,10 @@ func (client ExpressRouteCircuitsClient) ListResponder(resp *http.Response) (res } // ListNextResults retrieves the next set of results, if any. -func (client ExpressRouteCircuitsClient) ListNextResults(lastResults ExpressRouteCircuitListResult) (result ExpressRouteCircuitListResult, ae error) { +func (client ExpressRouteCircuitsClient) ListNextResults(lastResults ExpressRouteCircuitListResult) (result ExpressRouteCircuitListResult, err error) { req, err := lastResults.ExpressRouteCircuitListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -317,12 +325,12 @@ func (client ExpressRouteCircuitsClient) ListNextResults(lastResults ExpressRout resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "List", resp, "Failure responding to next results request request") } return @@ -330,21 +338,21 @@ func (client ExpressRouteCircuitsClient) ListNextResults(lastResults ExpressRout // ListAll the List ExpressRouteCircuit opertion retrieves all the // ExpressRouteCircuits in a subscription. -func (client ExpressRouteCircuitsClient) ListAll() (result ExpressRouteCircuitListResult, ae error) { +func (client ExpressRouteCircuitsClient) ListAll() (result ExpressRouteCircuitListResult, err error) { req, err := client.ListAllPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "ListAll", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListAll", nil, "Failure preparing request") } resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "ListAll", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListAll", resp, "Failure sending request") } result, err = client.ListAllResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "ListAll", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListAll", resp, "Failure responding to request") } return @@ -372,7 +380,7 @@ func (client ExpressRouteCircuitsClient) ListAllPreparer() (*http.Request, error // ListAllSender sends the ListAll request. The method will close the // http.Response Body if it receives an error. func (client ExpressRouteCircuitsClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListAllResponder handles the response to the ListAll request. The method always @@ -381,7 +389,7 @@ func (client ExpressRouteCircuitsClient) ListAllResponder(resp *http.Response) ( err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -389,10 +397,10 @@ func (client ExpressRouteCircuitsClient) ListAllResponder(resp *http.Response) ( } // ListAllNextResults retrieves the next set of results, if any. -func (client ExpressRouteCircuitsClient) ListAllNextResults(lastResults ExpressRouteCircuitListResult) (result ExpressRouteCircuitListResult, ae error) { +func (client ExpressRouteCircuitsClient) ListAllNextResults(lastResults ExpressRouteCircuitListResult) (result ExpressRouteCircuitListResult, err error) { req, err := lastResults.ExpressRouteCircuitListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "ListAll", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListAll", nil, "Failure preparing next results request request") } if req == nil { return @@ -401,12 +409,12 @@ func (client ExpressRouteCircuitsClient) ListAllNextResults(lastResults ExpressR resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "ListAll", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListAll", resp, "Failure sending next results request request") } result, err = client.ListAllResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "ListAll", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListAll", resp, "Failure responding to next results request request") } return @@ -418,21 +426,21 @@ func (client ExpressRouteCircuitsClient) ListAllNextResults(lastResults ExpressR // // resourceGroupName is the name of the resource group. circuitName is the // name of the circuit. -func (client ExpressRouteCircuitsClient) ListArpTable(resourceGroupName string, circuitName string) (result ExpressRouteCircuitsArpTableListResult, ae error) { +func (client ExpressRouteCircuitsClient) ListArpTable(resourceGroupName string, circuitName string) (result ExpressRouteCircuitsArpTableListResult, err error) { req, err := client.ListArpTablePreparer(resourceGroupName, circuitName) if err != nil { - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "ListArpTable", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListArpTable", nil, "Failure preparing request") } resp, err := client.ListArpTableSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "ListArpTable", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListArpTable", resp, "Failure sending request") } result, err = client.ListArpTableResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "ListArpTable", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListArpTable", resp, "Failure responding to request") } return @@ -462,7 +470,7 @@ func (client ExpressRouteCircuitsClient) ListArpTablePreparer(resourceGroupName // ListArpTableSender sends the ListArpTable request. The method will close the // http.Response Body if it receives an error. func (client ExpressRouteCircuitsClient) ListArpTableSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListArpTableResponder handles the response to the ListArpTable request. The method always @@ -471,7 +479,7 @@ func (client ExpressRouteCircuitsClient) ListArpTableResponder(resp *http.Respon err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -479,10 +487,10 @@ func (client ExpressRouteCircuitsClient) ListArpTableResponder(resp *http.Respon } // ListArpTableNextResults retrieves the next set of results, if any. -func (client ExpressRouteCircuitsClient) ListArpTableNextResults(lastResults ExpressRouteCircuitsArpTableListResult) (result ExpressRouteCircuitsArpTableListResult, ae error) { +func (client ExpressRouteCircuitsClient) ListArpTableNextResults(lastResults ExpressRouteCircuitsArpTableListResult) (result ExpressRouteCircuitsArpTableListResult, err error) { req, err := lastResults.ExpressRouteCircuitsArpTableListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "ListArpTable", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListArpTable", nil, "Failure preparing next results request request") } if req == nil { return @@ -491,12 +499,12 @@ func (client ExpressRouteCircuitsClient) ListArpTableNextResults(lastResults Exp resp, err := client.ListArpTableSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "ListArpTable", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListArpTable", resp, "Failure sending next results request request") } result, err = client.ListArpTableResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "ListArpTable", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListArpTable", resp, "Failure responding to next results request request") } return @@ -508,21 +516,21 @@ func (client ExpressRouteCircuitsClient) ListArpTableNextResults(lastResults Exp // // resourceGroupName is the name of the resource group. circuitName is the // name of the circuit. -func (client ExpressRouteCircuitsClient) ListRoutesTable(resourceGroupName string, circuitName string) (result ExpressRouteCircuitsRoutesTableListResult, ae error) { +func (client ExpressRouteCircuitsClient) ListRoutesTable(resourceGroupName string, circuitName string) (result ExpressRouteCircuitsRoutesTableListResult, err error) { req, err := client.ListRoutesTablePreparer(resourceGroupName, circuitName) if err != nil { - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "ListRoutesTable", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTable", nil, "Failure preparing request") } resp, err := client.ListRoutesTableSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "ListRoutesTable", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTable", resp, "Failure sending request") } result, err = client.ListRoutesTableResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "ListRoutesTable", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTable", resp, "Failure responding to request") } return @@ -552,7 +560,7 @@ func (client ExpressRouteCircuitsClient) ListRoutesTablePreparer(resourceGroupNa // ListRoutesTableSender sends the ListRoutesTable request. The method will close the // http.Response Body if it receives an error. func (client ExpressRouteCircuitsClient) ListRoutesTableSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListRoutesTableResponder handles the response to the ListRoutesTable request. The method always @@ -561,7 +569,7 @@ func (client ExpressRouteCircuitsClient) ListRoutesTableResponder(resp *http.Res err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -569,10 +577,10 @@ func (client ExpressRouteCircuitsClient) ListRoutesTableResponder(resp *http.Res } // ListRoutesTableNextResults retrieves the next set of results, if any. -func (client ExpressRouteCircuitsClient) ListRoutesTableNextResults(lastResults ExpressRouteCircuitsRoutesTableListResult) (result ExpressRouteCircuitsRoutesTableListResult, ae error) { +func (client ExpressRouteCircuitsClient) ListRoutesTableNextResults(lastResults ExpressRouteCircuitsRoutesTableListResult) (result ExpressRouteCircuitsRoutesTableListResult, err error) { req, err := lastResults.ExpressRouteCircuitsRoutesTableListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "ListRoutesTable", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTable", nil, "Failure preparing next results request request") } if req == nil { return @@ -581,12 +589,12 @@ func (client ExpressRouteCircuitsClient) ListRoutesTableNextResults(lastResults resp, err := client.ListRoutesTableSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "ListRoutesTable", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTable", resp, "Failure sending next results request request") } result, err = client.ListRoutesTableResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "ListRoutesTable", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTable", resp, "Failure responding to next results request request") } return @@ -597,21 +605,21 @@ func (client ExpressRouteCircuitsClient) ListRoutesTableNextResults(lastResults // // resourceGroupName is the name of the resource group. circuitName is the // name of the loadBalancer. -func (client ExpressRouteCircuitsClient) ListStats(resourceGroupName string, circuitName string) (result ExpressRouteCircuitsStatsListResult, ae error) { +func (client ExpressRouteCircuitsClient) ListStats(resourceGroupName string, circuitName string) (result ExpressRouteCircuitsStatsListResult, err error) { req, err := client.ListStatsPreparer(resourceGroupName, circuitName) if err != nil { - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "ListStats", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListStats", nil, "Failure preparing request") } resp, err := client.ListStatsSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "ListStats", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListStats", resp, "Failure sending request") } result, err = client.ListStatsResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "ListStats", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListStats", resp, "Failure responding to request") } return @@ -641,7 +649,7 @@ func (client ExpressRouteCircuitsClient) ListStatsPreparer(resourceGroupName str // ListStatsSender sends the ListStats request. The method will close the // http.Response Body if it receives an error. func (client ExpressRouteCircuitsClient) ListStatsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListStatsResponder handles the response to the ListStats request. The method always @@ -650,7 +658,7 @@ func (client ExpressRouteCircuitsClient) ListStatsResponder(resp *http.Response) err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -658,10 +666,10 @@ func (client ExpressRouteCircuitsClient) ListStatsResponder(resp *http.Response) } // ListStatsNextResults retrieves the next set of results, if any. -func (client ExpressRouteCircuitsClient) ListStatsNextResults(lastResults ExpressRouteCircuitsStatsListResult) (result ExpressRouteCircuitsStatsListResult, ae error) { +func (client ExpressRouteCircuitsClient) ListStatsNextResults(lastResults ExpressRouteCircuitsStatsListResult) (result ExpressRouteCircuitsStatsListResult, err error) { req, err := lastResults.ExpressRouteCircuitsStatsListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "ListStats", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListStats", nil, "Failure preparing next results request request") } if req == nil { return @@ -670,12 +678,12 @@ func (client ExpressRouteCircuitsClient) ListStatsNextResults(lastResults Expres resp, err := client.ListStatsSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "ListStats", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListStats", resp, "Failure sending next results request request") } result, err = client.ListStatsResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ExpressRouteCircuitsClient", "ListStats", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListStats", resp, "Failure responding to next results request request") } return diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/expressrouteserviceproviders.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/expressrouteserviceproviders.go index 6250e16b4396..810243d2e3a1 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/expressrouteserviceproviders.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/expressrouteserviceproviders.go @@ -14,12 +14,13 @@ package network // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -47,21 +48,21 @@ func NewExpressRouteServiceProvidersClientWithBaseURI(baseURI string, subscripti // List the List ExpressRouteServiceProvider opertion retrieves all the // available ExpressRouteServiceProviders. -func (client ExpressRouteServiceProvidersClient) List() (result ExpressRouteServiceProviderListResult, ae error) { +func (client ExpressRouteServiceProvidersClient) List() (result ExpressRouteServiceProviderListResult, err error) { req, err := client.ListPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/ExpressRouteServiceProvidersClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/ExpressRouteServiceProvidersClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ExpressRouteServiceProvidersClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "List", resp, "Failure responding to request") } return @@ -89,7 +90,7 @@ func (client ExpressRouteServiceProvidersClient) ListPreparer() (*http.Request, // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client ExpressRouteServiceProvidersClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -98,7 +99,7 @@ func (client ExpressRouteServiceProvidersClient) ListResponder(resp *http.Respon err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -106,10 +107,10 @@ func (client ExpressRouteServiceProvidersClient) ListResponder(resp *http.Respon } // ListNextResults retrieves the next set of results, if any. -func (client ExpressRouteServiceProvidersClient) ListNextResults(lastResults ExpressRouteServiceProviderListResult) (result ExpressRouteServiceProviderListResult, ae error) { +func (client ExpressRouteServiceProvidersClient) ListNextResults(lastResults ExpressRouteServiceProviderListResult) (result ExpressRouteServiceProviderListResult, err error) { req, err := lastResults.ExpressRouteServiceProviderListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/ExpressRouteServiceProvidersClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -118,12 +119,12 @@ func (client ExpressRouteServiceProvidersClient) ListNextResults(lastResults Exp resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/ExpressRouteServiceProvidersClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/ExpressRouteServiceProvidersClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "List", resp, "Failure responding to next results request request") } return diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/interfaces.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/interfaces.go index 0bf08a736978..b14b21b253b9 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/interfaces.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/interfaces.go @@ -14,12 +14,13 @@ package network // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -45,33 +46,35 @@ func NewInterfacesClientWithBaseURI(baseURI string, subscriptionID string) Inter } // CreateOrUpdate the Put NetworkInterface operation creates/updates a -// networkInterface +// networkInterface This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. networkInterfaceName // is the name of the network interface. parameters is parameters supplied to // the create/update NetworkInterface operation -func (client InterfacesClient) CreateOrUpdate(resourceGroupName string, networkInterfaceName string, parameters Interface) (result Interface, ae error) { - req, err := client.CreateOrUpdatePreparer(resourceGroupName, networkInterfaceName, parameters) +func (client InterfacesClient) CreateOrUpdate(resourceGroupName string, networkInterfaceName string, parameters Interface, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, networkInterfaceName, parameters, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/InterfacesClient", "CreateOrUpdate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "CreateOrUpdate", nil, "Failure preparing request") } resp, err := client.CreateOrUpdateSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/InterfacesClient", "CreateOrUpdate", resp.StatusCode, "Failure sending request") + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "CreateOrUpdate", resp, "Failure sending request") } result, err = client.CreateOrUpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/InterfacesClient", "CreateOrUpdate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "CreateOrUpdate", resp, "Failure responding to request") } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client InterfacesClient) CreateOrUpdatePreparer(resourceGroupName string, networkInterfaceName string, parameters Interface) (*http.Request, error) { +func (client InterfacesClient) CreateOrUpdatePreparer(resourceGroupName string, networkInterfaceName string, parameters Interface, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "networkInterfaceName": url.QueryEscape(networkInterfaceName), "resourceGroupName": url.QueryEscape(resourceGroupName), @@ -82,7 +85,7 @@ func (client InterfacesClient) CreateOrUpdatePreparer(resourceGroupName string, "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), @@ -95,49 +98,52 @@ func (client InterfacesClient) CreateOrUpdatePreparer(resourceGroupName string, // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client InterfacesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusCreated, http.StatusOK) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client InterfacesClient) CreateOrUpdateResponder(resp *http.Response) (result Interface, err error) { +func (client InterfacesClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), - autorest.ByUnmarshallingJSON(&result), + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + result.Response = resp return } // Delete the delete netwokInterface operation deletes the specified -// netwokInterface. +// netwokInterface. This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. networkInterfaceName // is the name of the network interface. -func (client InterfacesClient) Delete(resourceGroupName string, networkInterfaceName string) (result autorest.Response, ae error) { - req, err := client.DeletePreparer(resourceGroupName, networkInterfaceName) +func (client InterfacesClient) Delete(resourceGroupName string, networkInterfaceName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, networkInterfaceName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/InterfacesClient", "Delete", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "Delete", nil, "Failure preparing request") } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "network/InterfacesClient", "Delete", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "Delete", resp, "Failure sending request") } result, err = client.DeleteResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/InterfacesClient", "Delete", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "Delete", resp, "Failure responding to request") } return } // DeletePreparer prepares the Delete request. -func (client InterfacesClient) DeletePreparer(resourceGroupName string, networkInterfaceName string) (*http.Request, error) { +func (client InterfacesClient) DeletePreparer(resourceGroupName string, networkInterfaceName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "networkInterfaceName": url.QueryEscape(networkInterfaceName), "resourceGroupName": url.QueryEscape(resourceGroupName), @@ -148,7 +154,7 @@ func (client InterfacesClient) DeletePreparer(resourceGroupName string, networkI "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), @@ -160,7 +166,9 @@ func (client InterfacesClient) DeletePreparer(resourceGroupName string, networkI // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client InterfacesClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusNoContent, http.StatusAccepted, http.StatusOK) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // DeleteResponder handles the response to the Delete request. The method always @@ -169,7 +177,7 @@ func (client InterfacesClient) DeleteResponder(resp *http.Response) (result auto err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusAccepted, http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusAccepted, http.StatusOK), autorest.ByClosing()) result.Response = resp return @@ -181,21 +189,21 @@ func (client InterfacesClient) DeleteResponder(resp *http.Response) (result auto // resourceGroupName is the name of the resource group. networkInterfaceName // is the name of the network interface. expand is expand references // resources. -func (client InterfacesClient) Get(resourceGroupName string, networkInterfaceName string, expand string) (result Interface, ae error) { +func (client InterfacesClient) Get(resourceGroupName string, networkInterfaceName string, expand string) (result Interface, err error) { req, err := client.GetPreparer(resourceGroupName, networkInterfaceName, expand) if err != nil { - return result, autorest.NewErrorWithError(err, "network/InterfacesClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/InterfacesClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/InterfacesClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "Get", resp, "Failure responding to request") } return @@ -228,7 +236,7 @@ func (client InterfacesClient) GetPreparer(resourceGroupName string, networkInte // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client InterfacesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -237,7 +245,7 @@ func (client InterfacesClient) GetResponder(resp *http.Response) (result Interfa err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -252,21 +260,21 @@ func (client InterfacesClient) GetResponder(resp *http.Response) (result Interfa // virtualMachineScaleSetName is the name of the virtual machine scale set. // virtualmachineIndex is the virtual machine index. networkInterfaceName is // the name of the network interface. expand is expand references resources. -func (client InterfacesClient) GetVirtualMachineScaleSetNetworkInterface(resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, expand string) (result Interface, ae error) { +func (client InterfacesClient) GetVirtualMachineScaleSetNetworkInterface(resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string, networkInterfaceName string, expand string) (result Interface, err error) { req, err := client.GetVirtualMachineScaleSetNetworkInterfacePreparer(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand) if err != nil { - return result, autorest.NewErrorWithError(err, "network/InterfacesClient", "GetVirtualMachineScaleSetNetworkInterface", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "GetVirtualMachineScaleSetNetworkInterface", nil, "Failure preparing request") } resp, err := client.GetVirtualMachineScaleSetNetworkInterfaceSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/InterfacesClient", "GetVirtualMachineScaleSetNetworkInterface", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "GetVirtualMachineScaleSetNetworkInterface", resp, "Failure sending request") } result, err = client.GetVirtualMachineScaleSetNetworkInterfaceResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/InterfacesClient", "GetVirtualMachineScaleSetNetworkInterface", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "GetVirtualMachineScaleSetNetworkInterface", resp, "Failure responding to request") } return @@ -301,7 +309,7 @@ func (client InterfacesClient) GetVirtualMachineScaleSetNetworkInterfacePreparer // GetVirtualMachineScaleSetNetworkInterfaceSender sends the GetVirtualMachineScaleSetNetworkInterface request. The method will close the // http.Response Body if it receives an error. func (client InterfacesClient) GetVirtualMachineScaleSetNetworkInterfaceSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetVirtualMachineScaleSetNetworkInterfaceResponder handles the response to the GetVirtualMachineScaleSetNetworkInterface request. The method always @@ -310,7 +318,7 @@ func (client InterfacesClient) GetVirtualMachineScaleSetNetworkInterfaceResponde err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -321,21 +329,21 @@ func (client InterfacesClient) GetVirtualMachineScaleSetNetworkInterfaceResponde // networkInterfaces in a resource group. // // resourceGroupName is the name of the resource group. -func (client InterfacesClient) List(resourceGroupName string) (result InterfaceListResult, ae error) { +func (client InterfacesClient) List(resourceGroupName string) (result InterfaceListResult, err error) { req, err := client.ListPreparer(resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "network/InterfacesClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/InterfacesClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/InterfacesClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "List", resp, "Failure responding to request") } return @@ -364,7 +372,7 @@ func (client InterfacesClient) ListPreparer(resourceGroupName string) (*http.Req // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client InterfacesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -373,7 +381,7 @@ func (client InterfacesClient) ListResponder(resp *http.Response) (result Interf err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -381,10 +389,10 @@ func (client InterfacesClient) ListResponder(resp *http.Response) (result Interf } // ListNextResults retrieves the next set of results, if any. -func (client InterfacesClient) ListNextResults(lastResults InterfaceListResult) (result InterfaceListResult, ae error) { +func (client InterfacesClient) ListNextResults(lastResults InterfaceListResult) (result InterfaceListResult, err error) { req, err := lastResults.InterfaceListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/InterfacesClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -393,12 +401,12 @@ func (client InterfacesClient) ListNextResults(lastResults InterfaceListResult) resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/InterfacesClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/InterfacesClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "List", resp, "Failure responding to next results request request") } return @@ -406,21 +414,21 @@ func (client InterfacesClient) ListNextResults(lastResults InterfaceListResult) // ListAll the List networkInterfaces opertion retrieves all the // networkInterfaces in a subscription. -func (client InterfacesClient) ListAll() (result InterfaceListResult, ae error) { +func (client InterfacesClient) ListAll() (result InterfaceListResult, err error) { req, err := client.ListAllPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/InterfacesClient", "ListAll", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "ListAll", nil, "Failure preparing request") } resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/InterfacesClient", "ListAll", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "ListAll", resp, "Failure sending request") } result, err = client.ListAllResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/InterfacesClient", "ListAll", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListAll", resp, "Failure responding to request") } return @@ -448,7 +456,7 @@ func (client InterfacesClient) ListAllPreparer() (*http.Request, error) { // ListAllSender sends the ListAll request. The method will close the // http.Response Body if it receives an error. func (client InterfacesClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListAllResponder handles the response to the ListAll request. The method always @@ -457,7 +465,7 @@ func (client InterfacesClient) ListAllResponder(resp *http.Response) (result Int err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -465,10 +473,10 @@ func (client InterfacesClient) ListAllResponder(resp *http.Response) (result Int } // ListAllNextResults retrieves the next set of results, if any. -func (client InterfacesClient) ListAllNextResults(lastResults InterfaceListResult) (result InterfaceListResult, ae error) { +func (client InterfacesClient) ListAllNextResults(lastResults InterfaceListResult) (result InterfaceListResult, err error) { req, err := lastResults.InterfaceListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/InterfacesClient", "ListAll", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "ListAll", nil, "Failure preparing next results request request") } if req == nil { return @@ -477,12 +485,12 @@ func (client InterfacesClient) ListAllNextResults(lastResults InterfaceListResul resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/InterfacesClient", "ListAll", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "ListAll", resp, "Failure sending next results request request") } result, err = client.ListAllResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/InterfacesClient", "ListAll", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListAll", resp, "Failure responding to next results request request") } return @@ -494,21 +502,21 @@ func (client InterfacesClient) ListAllNextResults(lastResults InterfaceListResul // // resourceGroupName is the name of the resource group. // virtualMachineScaleSetName is the name of the virtual machine scale set. -func (client InterfacesClient) ListVirtualMachineScaleSetNetworkInterfaces(resourceGroupName string, virtualMachineScaleSetName string) (result InterfaceListResult, ae error) { +func (client InterfacesClient) ListVirtualMachineScaleSetNetworkInterfaces(resourceGroupName string, virtualMachineScaleSetName string) (result InterfaceListResult, err error) { req, err := client.ListVirtualMachineScaleSetNetworkInterfacesPreparer(resourceGroupName, virtualMachineScaleSetName) if err != nil { - return result, autorest.NewErrorWithError(err, "network/InterfacesClient", "ListVirtualMachineScaleSetNetworkInterfaces", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetNetworkInterfaces", nil, "Failure preparing request") } resp, err := client.ListVirtualMachineScaleSetNetworkInterfacesSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/InterfacesClient", "ListVirtualMachineScaleSetNetworkInterfaces", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetNetworkInterfaces", resp, "Failure sending request") } result, err = client.ListVirtualMachineScaleSetNetworkInterfacesResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/InterfacesClient", "ListVirtualMachineScaleSetNetworkInterfaces", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetNetworkInterfaces", resp, "Failure responding to request") } return @@ -538,7 +546,7 @@ func (client InterfacesClient) ListVirtualMachineScaleSetNetworkInterfacesPrepar // ListVirtualMachineScaleSetNetworkInterfacesSender sends the ListVirtualMachineScaleSetNetworkInterfaces request. The method will close the // http.Response Body if it receives an error. func (client InterfacesClient) ListVirtualMachineScaleSetNetworkInterfacesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListVirtualMachineScaleSetNetworkInterfacesResponder handles the response to the ListVirtualMachineScaleSetNetworkInterfaces request. The method always @@ -547,7 +555,7 @@ func (client InterfacesClient) ListVirtualMachineScaleSetNetworkInterfacesRespon err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -555,10 +563,10 @@ func (client InterfacesClient) ListVirtualMachineScaleSetNetworkInterfacesRespon } // ListVirtualMachineScaleSetNetworkInterfacesNextResults retrieves the next set of results, if any. -func (client InterfacesClient) ListVirtualMachineScaleSetNetworkInterfacesNextResults(lastResults InterfaceListResult) (result InterfaceListResult, ae error) { +func (client InterfacesClient) ListVirtualMachineScaleSetNetworkInterfacesNextResults(lastResults InterfaceListResult) (result InterfaceListResult, err error) { req, err := lastResults.InterfaceListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/InterfacesClient", "ListVirtualMachineScaleSetNetworkInterfaces", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetNetworkInterfaces", nil, "Failure preparing next results request request") } if req == nil { return @@ -567,12 +575,12 @@ func (client InterfacesClient) ListVirtualMachineScaleSetNetworkInterfacesNextRe resp, err := client.ListVirtualMachineScaleSetNetworkInterfacesSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/InterfacesClient", "ListVirtualMachineScaleSetNetworkInterfaces", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetNetworkInterfaces", resp, "Failure sending next results request request") } result, err = client.ListVirtualMachineScaleSetNetworkInterfacesResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/InterfacesClient", "ListVirtualMachineScaleSetNetworkInterfaces", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetNetworkInterfaces", resp, "Failure responding to next results request request") } return @@ -585,21 +593,21 @@ func (client InterfacesClient) ListVirtualMachineScaleSetNetworkInterfacesNextRe // resourceGroupName is the name of the resource group. // virtualMachineScaleSetName is the name of the virtual machine scale set. // virtualmachineIndex is the virtual machine index. -func (client InterfacesClient) ListVirtualMachineScaleSetVMNetworkInterfaces(resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string) (result InterfaceListResult, ae error) { +func (client InterfacesClient) ListVirtualMachineScaleSetVMNetworkInterfaces(resourceGroupName string, virtualMachineScaleSetName string, virtualmachineIndex string) (result InterfaceListResult, err error) { req, err := client.ListVirtualMachineScaleSetVMNetworkInterfacesPreparer(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex) if err != nil { - return result, autorest.NewErrorWithError(err, "network/InterfacesClient", "ListVirtualMachineScaleSetVMNetworkInterfaces", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetVMNetworkInterfaces", nil, "Failure preparing request") } resp, err := client.ListVirtualMachineScaleSetVMNetworkInterfacesSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/InterfacesClient", "ListVirtualMachineScaleSetVMNetworkInterfaces", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetVMNetworkInterfaces", resp, "Failure sending request") } result, err = client.ListVirtualMachineScaleSetVMNetworkInterfacesResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/InterfacesClient", "ListVirtualMachineScaleSetVMNetworkInterfaces", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetVMNetworkInterfaces", resp, "Failure responding to request") } return @@ -630,7 +638,7 @@ func (client InterfacesClient) ListVirtualMachineScaleSetVMNetworkInterfacesPrep // ListVirtualMachineScaleSetVMNetworkInterfacesSender sends the ListVirtualMachineScaleSetVMNetworkInterfaces request. The method will close the // http.Response Body if it receives an error. func (client InterfacesClient) ListVirtualMachineScaleSetVMNetworkInterfacesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListVirtualMachineScaleSetVMNetworkInterfacesResponder handles the response to the ListVirtualMachineScaleSetVMNetworkInterfaces request. The method always @@ -639,7 +647,7 @@ func (client InterfacesClient) ListVirtualMachineScaleSetVMNetworkInterfacesResp err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -647,10 +655,10 @@ func (client InterfacesClient) ListVirtualMachineScaleSetVMNetworkInterfacesResp } // ListVirtualMachineScaleSetVMNetworkInterfacesNextResults retrieves the next set of results, if any. -func (client InterfacesClient) ListVirtualMachineScaleSetVMNetworkInterfacesNextResults(lastResults InterfaceListResult) (result InterfaceListResult, ae error) { +func (client InterfacesClient) ListVirtualMachineScaleSetVMNetworkInterfacesNextResults(lastResults InterfaceListResult) (result InterfaceListResult, err error) { req, err := lastResults.InterfaceListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/InterfacesClient", "ListVirtualMachineScaleSetVMNetworkInterfaces", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetVMNetworkInterfaces", nil, "Failure preparing next results request request") } if req == nil { return @@ -659,12 +667,12 @@ func (client InterfacesClient) ListVirtualMachineScaleSetVMNetworkInterfacesNext resp, err := client.ListVirtualMachineScaleSetVMNetworkInterfacesSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/InterfacesClient", "ListVirtualMachineScaleSetVMNetworkInterfaces", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetVMNetworkInterfaces", resp, "Failure sending next results request request") } result, err = client.ListVirtualMachineScaleSetVMNetworkInterfacesResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/InterfacesClient", "ListVirtualMachineScaleSetVMNetworkInterfaces", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetVMNetworkInterfaces", resp, "Failure responding to next results request request") } return diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/loadbalancers.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/loadbalancers.go index a36a34f46af1..f74225f8df16 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/loadbalancers.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/loadbalancers.go @@ -14,12 +14,13 @@ package network // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -45,33 +46,36 @@ func NewLoadBalancersClientWithBaseURI(baseURI string, subscriptionID string) Lo return LoadBalancersClient{NewWithBaseURI(baseURI, subscriptionID)} } -// CreateOrUpdate the Put LoadBalancer operation creates/updates a LoadBalancer +// CreateOrUpdate the Put LoadBalancer operation creates/updates a +// LoadBalancer This method may poll for completion. Polling can be canceled +// by passing the cancel channel argument. The channel will be used to cancel +// polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. loadBalancerName is // the name of the loadBalancer. parameters is parameters supplied to the // create/delete LoadBalancer operation -func (client LoadBalancersClient) CreateOrUpdate(resourceGroupName string, loadBalancerName string, parameters LoadBalancer) (result LoadBalancer, ae error) { - req, err := client.CreateOrUpdatePreparer(resourceGroupName, loadBalancerName, parameters) +func (client LoadBalancersClient) CreateOrUpdate(resourceGroupName string, loadBalancerName string, parameters LoadBalancer, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, loadBalancerName, parameters, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/LoadBalancersClient", "CreateOrUpdate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "CreateOrUpdate", nil, "Failure preparing request") } resp, err := client.CreateOrUpdateSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/LoadBalancersClient", "CreateOrUpdate", resp.StatusCode, "Failure sending request") + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "CreateOrUpdate", resp, "Failure sending request") } result, err = client.CreateOrUpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/LoadBalancersClient", "CreateOrUpdate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "CreateOrUpdate", resp, "Failure responding to request") } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client LoadBalancersClient) CreateOrUpdatePreparer(resourceGroupName string, loadBalancerName string, parameters LoadBalancer) (*http.Request, error) { +func (client LoadBalancersClient) CreateOrUpdatePreparer(resourceGroupName string, loadBalancerName string, parameters LoadBalancer, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "loadBalancerName": url.QueryEscape(loadBalancerName), "resourceGroupName": url.QueryEscape(resourceGroupName), @@ -82,7 +86,7 @@ func (client LoadBalancersClient) CreateOrUpdatePreparer(resourceGroupName strin "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), @@ -95,48 +99,52 @@ func (client LoadBalancersClient) CreateOrUpdatePreparer(resourceGroupName strin // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client LoadBalancersClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusCreated, http.StatusOK) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client LoadBalancersClient) CreateOrUpdateResponder(resp *http.Response) (result LoadBalancer, err error) { +func (client LoadBalancersClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), - autorest.ByUnmarshallingJSON(&result), + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + result.Response = resp return } -// Delete the delete loadbalancer operation deletes the specified loadbalancer. +// Delete the delete loadbalancer operation deletes the specified +// loadbalancer. This method may poll for completion. Polling can be canceled +// by passing the cancel channel argument. The channel will be used to cancel +// polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. loadBalancerName is // the name of the loadBalancer. -func (client LoadBalancersClient) Delete(resourceGroupName string, loadBalancerName string) (result autorest.Response, ae error) { - req, err := client.DeletePreparer(resourceGroupName, loadBalancerName) +func (client LoadBalancersClient) Delete(resourceGroupName string, loadBalancerName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, loadBalancerName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/LoadBalancersClient", "Delete", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Delete", nil, "Failure preparing request") } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "network/LoadBalancersClient", "Delete", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Delete", resp, "Failure sending request") } result, err = client.DeleteResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/LoadBalancersClient", "Delete", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Delete", resp, "Failure responding to request") } return } // DeletePreparer prepares the Delete request. -func (client LoadBalancersClient) DeletePreparer(resourceGroupName string, loadBalancerName string) (*http.Request, error) { +func (client LoadBalancersClient) DeletePreparer(resourceGroupName string, loadBalancerName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "loadBalancerName": url.QueryEscape(loadBalancerName), "resourceGroupName": url.QueryEscape(resourceGroupName), @@ -147,7 +155,7 @@ func (client LoadBalancersClient) DeletePreparer(resourceGroupName string, loadB "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), @@ -159,7 +167,9 @@ func (client LoadBalancersClient) DeletePreparer(resourceGroupName string, loadB // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client LoadBalancersClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusNoContent, http.StatusAccepted, http.StatusOK) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // DeleteResponder handles the response to the Delete request. The method always @@ -168,7 +178,7 @@ func (client LoadBalancersClient) DeleteResponder(resp *http.Response) (result a err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusAccepted, http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusAccepted, http.StatusOK), autorest.ByClosing()) result.Response = resp return @@ -179,21 +189,21 @@ func (client LoadBalancersClient) DeleteResponder(resp *http.Response) (result a // // resourceGroupName is the name of the resource group. loadBalancerName is // the name of the loadBalancer. expand is expand references resources. -func (client LoadBalancersClient) Get(resourceGroupName string, loadBalancerName string, expand string) (result LoadBalancer, ae error) { +func (client LoadBalancersClient) Get(resourceGroupName string, loadBalancerName string, expand string) (result LoadBalancer, err error) { req, err := client.GetPreparer(resourceGroupName, loadBalancerName, expand) if err != nil { - return result, autorest.NewErrorWithError(err, "network/LoadBalancersClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/LoadBalancersClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/LoadBalancersClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Get", resp, "Failure responding to request") } return @@ -226,7 +236,7 @@ func (client LoadBalancersClient) GetPreparer(resourceGroupName string, loadBala // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client LoadBalancersClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -235,7 +245,7 @@ func (client LoadBalancersClient) GetResponder(resp *http.Response) (result Load err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -246,21 +256,21 @@ func (client LoadBalancersClient) GetResponder(resp *http.Response) (result Load // resource group. // // resourceGroupName is the name of the resource group. -func (client LoadBalancersClient) List(resourceGroupName string) (result LoadBalancerListResult, ae error) { +func (client LoadBalancersClient) List(resourceGroupName string) (result LoadBalancerListResult, err error) { req, err := client.ListPreparer(resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "network/LoadBalancersClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/LoadBalancersClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/LoadBalancersClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "List", resp, "Failure responding to request") } return @@ -289,7 +299,7 @@ func (client LoadBalancersClient) ListPreparer(resourceGroupName string) (*http. // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client LoadBalancersClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -298,7 +308,7 @@ func (client LoadBalancersClient) ListResponder(resp *http.Response) (result Loa err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -306,10 +316,10 @@ func (client LoadBalancersClient) ListResponder(resp *http.Response) (result Loa } // ListNextResults retrieves the next set of results, if any. -func (client LoadBalancersClient) ListNextResults(lastResults LoadBalancerListResult) (result LoadBalancerListResult, ae error) { +func (client LoadBalancersClient) ListNextResults(lastResults LoadBalancerListResult) (result LoadBalancerListResult, err error) { req, err := lastResults.LoadBalancerListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/LoadBalancersClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -318,12 +328,12 @@ func (client LoadBalancersClient) ListNextResults(lastResults LoadBalancerListRe resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/LoadBalancersClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/LoadBalancersClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "List", resp, "Failure responding to next results request request") } return @@ -331,21 +341,21 @@ func (client LoadBalancersClient) ListNextResults(lastResults LoadBalancerListRe // ListAll the List loadBalancer opertion retrieves all the loadbalancers in a // subscription. -func (client LoadBalancersClient) ListAll() (result LoadBalancerListResult, ae error) { +func (client LoadBalancersClient) ListAll() (result LoadBalancerListResult, err error) { req, err := client.ListAllPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/LoadBalancersClient", "ListAll", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListAll", nil, "Failure preparing request") } resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/LoadBalancersClient", "ListAll", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListAll", resp, "Failure sending request") } result, err = client.ListAllResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/LoadBalancersClient", "ListAll", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListAll", resp, "Failure responding to request") } return @@ -373,7 +383,7 @@ func (client LoadBalancersClient) ListAllPreparer() (*http.Request, error) { // ListAllSender sends the ListAll request. The method will close the // http.Response Body if it receives an error. func (client LoadBalancersClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListAllResponder handles the response to the ListAll request. The method always @@ -382,7 +392,7 @@ func (client LoadBalancersClient) ListAllResponder(resp *http.Response) (result err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -390,10 +400,10 @@ func (client LoadBalancersClient) ListAllResponder(resp *http.Response) (result } // ListAllNextResults retrieves the next set of results, if any. -func (client LoadBalancersClient) ListAllNextResults(lastResults LoadBalancerListResult) (result LoadBalancerListResult, ae error) { +func (client LoadBalancersClient) ListAllNextResults(lastResults LoadBalancerListResult) (result LoadBalancerListResult, err error) { req, err := lastResults.LoadBalancerListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/LoadBalancersClient", "ListAll", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListAll", nil, "Failure preparing next results request request") } if req == nil { return @@ -402,12 +412,12 @@ func (client LoadBalancersClient) ListAllNextResults(lastResults LoadBalancerLis resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/LoadBalancersClient", "ListAll", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListAll", resp, "Failure sending next results request request") } result, err = client.ListAllResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/LoadBalancersClient", "ListAll", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListAll", resp, "Failure responding to next results request request") } return diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/localnetworkgateways.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/localnetworkgateways.go index 56116bf34f91..2c3c99f06e29 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/localnetworkgateways.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/localnetworkgateways.go @@ -14,12 +14,13 @@ package network // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -47,34 +48,36 @@ func NewLocalNetworkGatewaysClientWithBaseURI(baseURI string, subscriptionID str // CreateOrUpdate the Put LocalNetworkGateway operation creates/updates a // local network gateway in the specified resource group through Network -// resource provider. +// resource provider. This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. // localNetworkGatewayName is the name of the local network gateway. // parameters is parameters supplied to the Begin Create or update Local // Network Gateway operation through Network resource provider. -func (client LocalNetworkGatewaysClient) CreateOrUpdate(resourceGroupName string, localNetworkGatewayName string, parameters LocalNetworkGateway) (result LocalNetworkGateway, ae error) { - req, err := client.CreateOrUpdatePreparer(resourceGroupName, localNetworkGatewayName, parameters) +func (client LocalNetworkGatewaysClient) CreateOrUpdate(resourceGroupName string, localNetworkGatewayName string, parameters LocalNetworkGateway, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, localNetworkGatewayName, parameters, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/LocalNetworkGatewaysClient", "CreateOrUpdate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "CreateOrUpdate", nil, "Failure preparing request") } resp, err := client.CreateOrUpdateSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/LocalNetworkGatewaysClient", "CreateOrUpdate", resp.StatusCode, "Failure sending request") + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "CreateOrUpdate", resp, "Failure sending request") } result, err = client.CreateOrUpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/LocalNetworkGatewaysClient", "CreateOrUpdate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "CreateOrUpdate", resp, "Failure responding to request") } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client LocalNetworkGatewaysClient) CreateOrUpdatePreparer(resourceGroupName string, localNetworkGatewayName string, parameters LocalNetworkGateway) (*http.Request, error) { +func (client LocalNetworkGatewaysClient) CreateOrUpdatePreparer(resourceGroupName string, localNetworkGatewayName string, parameters LocalNetworkGateway, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "localNetworkGatewayName": url.QueryEscape(localNetworkGatewayName), "resourceGroupName": url.QueryEscape(resourceGroupName), @@ -85,7 +88,7 @@ func (client LocalNetworkGatewaysClient) CreateOrUpdatePreparer(resourceGroupNam "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), @@ -98,49 +101,53 @@ func (client LocalNetworkGatewaysClient) CreateOrUpdatePreparer(resourceGroupNam // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client LocalNetworkGatewaysClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusCreated, http.StatusOK) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client LocalNetworkGatewaysClient) CreateOrUpdateResponder(resp *http.Response) (result LocalNetworkGateway, err error) { +func (client LocalNetworkGatewaysClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), - autorest.ByUnmarshallingJSON(&result), + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + result.Response = resp return } // Delete the Delete LocalNetworkGateway operation deletes the specifed local -// network Gateway through Network resource provider. +// network Gateway through Network resource provider. This method may poll +// for completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. // // resourceGroupName is the name of the resource group. // localNetworkGatewayName is the name of the local network gateway. -func (client LocalNetworkGatewaysClient) Delete(resourceGroupName string, localNetworkGatewayName string) (result autorest.Response, ae error) { - req, err := client.DeletePreparer(resourceGroupName, localNetworkGatewayName) +func (client LocalNetworkGatewaysClient) Delete(resourceGroupName string, localNetworkGatewayName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, localNetworkGatewayName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/LocalNetworkGatewaysClient", "Delete", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "Delete", nil, "Failure preparing request") } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "network/LocalNetworkGatewaysClient", "Delete", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "Delete", resp, "Failure sending request") } result, err = client.DeleteResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/LocalNetworkGatewaysClient", "Delete", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "Delete", resp, "Failure responding to request") } return } // DeletePreparer prepares the Delete request. -func (client LocalNetworkGatewaysClient) DeletePreparer(resourceGroupName string, localNetworkGatewayName string) (*http.Request, error) { +func (client LocalNetworkGatewaysClient) DeletePreparer(resourceGroupName string, localNetworkGatewayName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "localNetworkGatewayName": url.QueryEscape(localNetworkGatewayName), "resourceGroupName": url.QueryEscape(resourceGroupName), @@ -151,11 +158,11 @@ func (client LocalNetworkGatewaysClient) DeletePreparer(resourceGroupName string "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), - autorest.WithPath("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways/{localNetworkGatewayName}/"), + autorest.WithPath("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways/{localNetworkGatewayName}"), autorest.WithPathParameters(pathParameters), autorest.WithQueryParameters(queryParameters)) } @@ -163,7 +170,9 @@ func (client LocalNetworkGatewaysClient) DeletePreparer(resourceGroupName string // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client LocalNetworkGatewaysClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusNoContent, http.StatusOK, http.StatusAccepted) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // DeleteResponder handles the response to the Delete request. The method always @@ -172,7 +181,7 @@ func (client LocalNetworkGatewaysClient) DeleteResponder(resp *http.Response) (r err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusOK, http.StatusAccepted), + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return @@ -183,21 +192,21 @@ func (client LocalNetworkGatewaysClient) DeleteResponder(resp *http.Response) (r // // resourceGroupName is the name of the resource group. // localNetworkGatewayName is the name of the local network gateway. -func (client LocalNetworkGatewaysClient) Get(resourceGroupName string, localNetworkGatewayName string) (result LocalNetworkGateway, ae error) { +func (client LocalNetworkGatewaysClient) Get(resourceGroupName string, localNetworkGatewayName string) (result LocalNetworkGateway, err error) { req, err := client.GetPreparer(resourceGroupName, localNetworkGatewayName) if err != nil { - return result, autorest.NewErrorWithError(err, "network/LocalNetworkGatewaysClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/LocalNetworkGatewaysClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/LocalNetworkGatewaysClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "Get", resp, "Failure responding to request") } return @@ -227,7 +236,7 @@ func (client LocalNetworkGatewaysClient) GetPreparer(resourceGroupName string, l // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client LocalNetworkGatewaysClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -236,7 +245,7 @@ func (client LocalNetworkGatewaysClient) GetResponder(resp *http.Response) (resu err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -247,21 +256,21 @@ func (client LocalNetworkGatewaysClient) GetResponder(resp *http.Response) (resu // gateways stored. // // resourceGroupName is the name of the resource group. -func (client LocalNetworkGatewaysClient) List(resourceGroupName string) (result LocalNetworkGatewayListResult, ae error) { +func (client LocalNetworkGatewaysClient) List(resourceGroupName string) (result LocalNetworkGatewayListResult, err error) { req, err := client.ListPreparer(resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "network/LocalNetworkGatewaysClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/LocalNetworkGatewaysClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/LocalNetworkGatewaysClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "List", resp, "Failure responding to request") } return @@ -290,7 +299,7 @@ func (client LocalNetworkGatewaysClient) ListPreparer(resourceGroupName string) // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client LocalNetworkGatewaysClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -299,7 +308,7 @@ func (client LocalNetworkGatewaysClient) ListResponder(resp *http.Response) (res err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -307,10 +316,10 @@ func (client LocalNetworkGatewaysClient) ListResponder(resp *http.Response) (res } // ListNextResults retrieves the next set of results, if any. -func (client LocalNetworkGatewaysClient) ListNextResults(lastResults LocalNetworkGatewayListResult) (result LocalNetworkGatewayListResult, ae error) { +func (client LocalNetworkGatewaysClient) ListNextResults(lastResults LocalNetworkGatewayListResult) (result LocalNetworkGatewayListResult, err error) { req, err := lastResults.LocalNetworkGatewayListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/LocalNetworkGatewaysClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -319,12 +328,12 @@ func (client LocalNetworkGatewaysClient) ListNextResults(lastResults LocalNetwor resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/LocalNetworkGatewaysClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/LocalNetworkGatewaysClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "List", resp, "Failure responding to next results request request") } return diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/models.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/models.go index 5e23a26e25c4..9e60cb47558c 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/models.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/models.go @@ -14,13 +14,13 @@ package network // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/to" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/to" "net/http" ) @@ -487,10 +487,10 @@ type ApplicationGatewayBackendHTTPSettings struct { // ApplicationGatewayBackendHTTPSettingsPropertiesFormat is properties of // Backend address pool settings of application gateway type ApplicationGatewayBackendHTTPSettingsPropertiesFormat struct { - Port *int `json:"port,omitempty"` + Port *int32 `json:"port,omitempty"` Protocol ApplicationGatewayProtocol `json:"protocol,omitempty"` CookieBasedAffinity ApplicationGatewayCookieBasedAffinity `json:"cookieBasedAffinity,omitempty"` - RequestTimeout *int `json:"requestTimeout,omitempty"` + RequestTimeout *int32 `json:"requestTimeout,omitempty"` Probe *SubResource `json:"probe,omitempty"` ProvisioningState *string `json:"provisioningState,omitempty"` } @@ -525,7 +525,7 @@ type ApplicationGatewayFrontendPort struct { // ApplicationGatewayFrontendPortPropertiesFormat is properties of Frontend // Port of application gateway type ApplicationGatewayFrontendPortPropertiesFormat struct { - Port *int `json:"port,omitempty"` + Port *int32 `json:"port,omitempty"` ProvisioningState *string `json:"provisioningState,omitempty"` } @@ -616,9 +616,9 @@ type ApplicationGatewayProbePropertiesFormat struct { Protocol ApplicationGatewayProtocol `json:"protocol,omitempty"` Host *string `json:"host,omitempty"` Path *string `json:"path,omitempty"` - Interval *int `json:"interval,omitempty"` - Timeout *int `json:"timeout,omitempty"` - UnhealthyThreshold *int `json:"unhealthyThreshold,omitempty"` + Interval *int32 `json:"interval,omitempty"` + Timeout *int32 `json:"timeout,omitempty"` + UnhealthyThreshold *int32 `json:"unhealthyThreshold,omitempty"` ProvisioningState *string `json:"provisioningState,omitempty"` } @@ -664,7 +664,7 @@ type ApplicationGatewayRequestRoutingRulePropertiesFormat struct { type ApplicationGatewaySku struct { Name ApplicationGatewaySkuName `json:"name,omitempty"` Tier ApplicationGatewayTier `json:"tier,omitempty"` - Capacity *int `json:"capacity,omitempty"` + Capacity *int32 `json:"capacity,omitempty"` } // ApplicationGatewaySslCertificate is sSL certificates of application gateway @@ -760,7 +760,7 @@ type BackendAddressPoolPropertiesFormat struct { // ConnectionResetSharedKey is type ConnectionResetSharedKey struct { autorest.Response `json:"-"` - KeyLength *int32 `json:"keyLength,omitempty"` + KeyLength *int64 `json:"keyLength,omitempty"` } // ConnectionSharedKey is response for GetConnectionSharedKey Api servive call @@ -869,7 +869,7 @@ type ExpressRouteCircuitPeering struct { type ExpressRouteCircuitPeeringConfig struct { AdvertisedPublicPrefixes *[]string `json:"advertisedPublicPrefixes,omitempty"` AdvertisedPublicPrefixesState ExpressRouteCircuitPeeringAdvertisedPublicPrefixState `json:"advertisedPublicPrefixesState,omitempty"` - CustomerASN *int `json:"customerASN,omitempty"` + CustomerASN *int32 `json:"customerASN,omitempty"` RoutingRegistryName *string `json:"routingRegistryName,omitempty"` } @@ -897,14 +897,14 @@ func (client ExpressRouteCircuitPeeringListResult) ExpressRouteCircuitPeeringLis type ExpressRouteCircuitPeeringPropertiesFormat struct { PeeringType ExpressRouteCircuitPeeringType `json:"peeringType,omitempty"` State ExpressRouteCircuitPeeringState `json:"state,omitempty"` - AzureASN *int `json:"azureASN,omitempty"` - PeerASN *int `json:"peerASN,omitempty"` + AzureASN *int32 `json:"azureASN,omitempty"` + PeerASN *int32 `json:"peerASN,omitempty"` PrimaryPeerAddressPrefix *string `json:"primaryPeerAddressPrefix,omitempty"` SecondaryPeerAddressPrefix *string `json:"secondaryPeerAddressPrefix,omitempty"` PrimaryAzurePort *string `json:"primaryAzurePort,omitempty"` SecondaryAzurePort *string `json:"secondaryAzurePort,omitempty"` SharedKey *string `json:"sharedKey,omitempty"` - VlanID *int `json:"vlanId,omitempty"` + VlanID *int32 `json:"vlanId,omitempty"` MicrosoftPeeringConfig *ExpressRouteCircuitPeeringConfig `json:"microsoftPeeringConfig,omitempty"` Stats *ExpressRouteCircuitStats `json:"stats,omitempty"` ProvisioningState *string `json:"provisioningState,omitempty"` @@ -956,7 +956,7 @@ func (client ExpressRouteCircuitsArpTableListResult) ExpressRouteCircuitsArpTabl type ExpressRouteCircuitServiceProviderProperties struct { ServiceProviderName *string `json:"serviceProviderName,omitempty"` PeeringLocation *string `json:"peeringLocation,omitempty"` - BandwidthInMbps *int `json:"bandwidthInMbps,omitempty"` + BandwidthInMbps *int32 `json:"bandwidthInMbps,omitempty"` } // ExpressRouteCircuitSku is contains sku in an ExpressRouteCircuit @@ -1008,8 +1008,8 @@ func (client ExpressRouteCircuitsStatsListResult) ExpressRouteCircuitsStatsListR // ExpressRouteCircuitStats is contains Stats associated with the peering type ExpressRouteCircuitStats struct { - BytesIn *int `json:"bytesIn,omitempty"` - BytesOut *int `json:"bytesOut,omitempty"` + BytesIn *int32 `json:"bytesIn,omitempty"` + BytesOut *int32 `json:"bytesOut,omitempty"` } // ExpressRouteServiceProvider is expressRouteResourceProvider object @@ -1017,6 +1017,8 @@ type ExpressRouteServiceProvider struct { ID *string `json:"id,omitempty"` Name *string `json:"name,omitempty"` Type *string `json:"type,omitempty"` + Location *string `json:"location,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` Properties *ExpressRouteServiceProviderPropertiesFormat `json:"properties,omitempty"` } @@ -1024,7 +1026,7 @@ type ExpressRouteServiceProvider struct { // in ExpressRouteServiceProviders type ExpressRouteServiceProviderBandwidthsOffered struct { OfferName *string `json:"offerName,omitempty"` - ValueInMbps *int `json:"valueInMbps,omitempty"` + ValueInMbps *int32 `json:"valueInMbps,omitempty"` } // ExpressRouteServiceProviderListResult is response for @@ -1089,9 +1091,9 @@ type InboundNatPool struct { type InboundNatPoolPropertiesFormat struct { FrontendIPConfiguration *SubResource `json:"frontendIPConfiguration,omitempty"` Protocol TransportProtocol `json:"protocol,omitempty"` - FrontendPortRangeStart *int `json:"frontendPortRangeStart,omitempty"` - FrontendPortRangeEnd *int `json:"frontendPortRangeEnd,omitempty"` - BackendPort *int `json:"backendPort,omitempty"` + FrontendPortRangeStart *int32 `json:"frontendPortRangeStart,omitempty"` + FrontendPortRangeEnd *int32 `json:"frontendPortRangeEnd,omitempty"` + BackendPort *int32 `json:"backendPort,omitempty"` ProvisioningState *string `json:"provisioningState,omitempty"` } @@ -1108,9 +1110,9 @@ type InboundNatRulePropertiesFormat struct { FrontendIPConfiguration *SubResource `json:"frontendIPConfiguration,omitempty"` BackendIPConfiguration *InterfaceIPConfiguration `json:"backendIPConfiguration,omitempty"` Protocol TransportProtocol `json:"protocol,omitempty"` - FrontendPort *int `json:"frontendPort,omitempty"` - BackendPort *int `json:"backendPort,omitempty"` - IdleTimeoutInMinutes *int `json:"idleTimeoutInMinutes,omitempty"` + FrontendPort *int32 `json:"frontendPort,omitempty"` + BackendPort *int32 `json:"backendPort,omitempty"` + IdleTimeoutInMinutes *int32 `json:"idleTimeoutInMinutes,omitempty"` EnableFloatingIP *bool `json:"enableFloatingIP,omitempty"` ProvisioningState *string `json:"provisioningState,omitempty"` } @@ -1148,7 +1150,7 @@ type InterfaceIPConfigurationPropertiesFormat struct { LoadBalancerBackendAddressPools *[]BackendAddressPool `json:"loadBalancerBackendAddressPools,omitempty"` LoadBalancerInboundNatRules *[]InboundNatRule `json:"loadBalancerInboundNatRules,omitempty"` PrivateIPAddress *string `json:"privateIPAddress,omitempty"` - PrivateIPAllocationMethod *string `json:"privateIPAllocationMethod,omitempty"` + PrivateIPAllocationMethod IPAllocationMethod `json:"privateIPAllocationMethod,omitempty"` Subnet *Subnet `json:"subnet,omitempty"` PublicIPAddress *PublicIPAddress `json:"publicIPAddress,omitempty"` ProvisioningState *string `json:"provisioningState,omitempty"` @@ -1262,9 +1264,9 @@ type LoadBalancingRulePropertiesFormat struct { Probe *SubResource `json:"probe,omitempty"` Protocol TransportProtocol `json:"protocol,omitempty"` LoadDistribution LoadDistribution `json:"loadDistribution,omitempty"` - FrontendPort *int `json:"frontendPort,omitempty"` - BackendPort *int `json:"backendPort,omitempty"` - IdleTimeoutInMinutes *int `json:"idleTimeoutInMinutes,omitempty"` + FrontendPort *int32 `json:"frontendPort,omitempty"` + BackendPort *int32 `json:"backendPort,omitempty"` + IdleTimeoutInMinutes *int32 `json:"idleTimeoutInMinutes,omitempty"` EnableFloatingIP *bool `json:"enableFloatingIP,omitempty"` ProvisioningState *string `json:"provisioningState,omitempty"` } @@ -1319,7 +1321,7 @@ type OutboundNatRule struct { // OutboundNatRulePropertiesFormat is outbound NAT pool of the loadbalancer type OutboundNatRulePropertiesFormat struct { - AllocatedOutboundPorts *int `json:"allocatedOutboundPorts,omitempty"` + AllocatedOutboundPorts *int32 `json:"allocatedOutboundPorts,omitempty"` FrontendIPConfigurations *[]SubResource `json:"frontendIPConfigurations,omitempty"` BackendAddressPool *SubResource `json:"backendAddressPool,omitempty"` ProvisioningState *string `json:"provisioningState,omitempty"` @@ -1337,9 +1339,9 @@ type Probe struct { type ProbePropertiesFormat struct { LoadBalancingRules *[]SubResource `json:"loadBalancingRules,omitempty"` Protocol ProbeProtocol `json:"protocol,omitempty"` - Port *int `json:"port,omitempty"` - IntervalInSeconds *int `json:"intervalInSeconds,omitempty"` - NumberOfProbes *int `json:"numberOfProbes,omitempty"` + Port *int32 `json:"port,omitempty"` + IntervalInSeconds *int32 `json:"intervalInSeconds,omitempty"` + NumberOfProbes *int32 `json:"numberOfProbes,omitempty"` RequestPath *string `json:"requestPath,omitempty"` ProvisioningState *string `json:"provisioningState,omitempty"` } @@ -1390,7 +1392,7 @@ type PublicIPAddressPropertiesFormat struct { IPConfiguration *IPConfiguration `json:"ipConfiguration,omitempty"` DNSSettings *PublicIPAddressDNSSettings `json:"dnsSettings,omitempty"` IPAddress *string `json:"ipAddress,omitempty"` - IdleTimeoutInMinutes *int `json:"idleTimeoutInMinutes,omitempty"` + IdleTimeoutInMinutes *int32 `json:"idleTimeoutInMinutes,omitempty"` ResourceGUID *string `json:"resourceGuid,omitempty"` ProvisioningState *string `json:"provisioningState,omitempty"` } @@ -1558,7 +1560,7 @@ type SecurityRulePropertiesFormat struct { SourceAddressPrefix *string `json:"sourceAddressPrefix,omitempty"` DestinationAddressPrefix *string `json:"destinationAddressPrefix,omitempty"` Access SecurityRuleAccess `json:"access,omitempty"` - Priority *int `json:"priority,omitempty"` + Priority *int32 `json:"priority,omitempty"` Direction SecurityRuleDirection `json:"direction,omitempty"` ProvisioningState *string `json:"provisioningState,omitempty"` } @@ -1615,8 +1617,8 @@ type SubResource struct { // Usage is describes Network Resource Usage. type Usage struct { Unit UsageUnit `json:"unit,omitempty"` - CurrentValue *int32 `json:"currentValue,omitempty"` - Limit *int32 `json:"limit,omitempty"` + CurrentValue *int64 `json:"currentValue,omitempty"` + Limit *int64 `json:"limit,omitempty"` Name *UsageName `json:"name,omitempty"` } @@ -1710,11 +1712,11 @@ type VirtualNetworkGatewayConnectionPropertiesFormat struct { VirtualNetworkGateway2 *VirtualNetworkGateway `json:"virtualNetworkGateway2,omitempty"` LocalNetworkGateway2 *LocalNetworkGateway `json:"localNetworkGateway2,omitempty"` ConnectionType VirtualNetworkGatewayConnectionType `json:"connectionType,omitempty"` - RoutingWeight *int `json:"routingWeight,omitempty"` + RoutingWeight *int32 `json:"routingWeight,omitempty"` SharedKey *string `json:"sharedKey,omitempty"` ConnectionStatus VirtualNetworkGatewayConnectionStatus `json:"connectionStatus,omitempty"` - EgressBytesTransferred *int32 `json:"egressBytesTransferred,omitempty"` - IngressBytesTransferred *int32 `json:"ingressBytesTransferred,omitempty"` + EgressBytesTransferred *int64 `json:"egressBytesTransferred,omitempty"` + IngressBytesTransferred *int64 `json:"ingressBytesTransferred,omitempty"` Peer *SubResource `json:"peer,omitempty"` ResourceGUID *string `json:"resourceGuid,omitempty"` ProvisioningState *string `json:"provisioningState,omitempty"` @@ -1776,7 +1778,7 @@ type VirtualNetworkGatewayPropertiesFormat struct { type VirtualNetworkGatewaySku struct { Name VirtualNetworkGatewaySkuName `json:"name,omitempty"` Tier VirtualNetworkGatewaySkuTier `json:"tier,omitempty"` - Capacity *int `json:"capacity,omitempty"` + Capacity *int32 `json:"capacity,omitempty"` } // VirtualNetworkListResult is response for ListVirtualNetworks Api servive diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/publicipaddresses.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/publicipaddresses.go index 70cfd4efe7b2..c33d66908a02 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/publicipaddresses.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/publicipaddresses.go @@ -14,12 +14,13 @@ package network // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -46,33 +47,35 @@ func NewPublicIPAddressesClientWithBaseURI(baseURI string, subscriptionID string } // CreateOrUpdate the Put PublicIPAddress operation creates/updates a -// stable/dynamic PublicIP address +// stable/dynamic PublicIP address This method may poll for completion. +// Polling can be canceled by passing the cancel channel argument. The +// channel will be used to cancel polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. publicIPAddressName is // the name of the publicIpAddress. parameters is parameters supplied to the // create/update PublicIPAddress operation -func (client PublicIPAddressesClient) CreateOrUpdate(resourceGroupName string, publicIPAddressName string, parameters PublicIPAddress) (result PublicIPAddress, ae error) { - req, err := client.CreateOrUpdatePreparer(resourceGroupName, publicIPAddressName, parameters) +func (client PublicIPAddressesClient) CreateOrUpdate(resourceGroupName string, publicIPAddressName string, parameters PublicIPAddress, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, publicIPAddressName, parameters, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/PublicIPAddressesClient", "CreateOrUpdate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "CreateOrUpdate", nil, "Failure preparing request") } resp, err := client.CreateOrUpdateSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/PublicIPAddressesClient", "CreateOrUpdate", resp.StatusCode, "Failure sending request") + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "CreateOrUpdate", resp, "Failure sending request") } result, err = client.CreateOrUpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/PublicIPAddressesClient", "CreateOrUpdate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "CreateOrUpdate", resp, "Failure responding to request") } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client PublicIPAddressesClient) CreateOrUpdatePreparer(resourceGroupName string, publicIPAddressName string, parameters PublicIPAddress) (*http.Request, error) { +func (client PublicIPAddressesClient) CreateOrUpdatePreparer(resourceGroupName string, publicIPAddressName string, parameters PublicIPAddress, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "publicIpAddressName": url.QueryEscape(publicIPAddressName), "resourceGroupName": url.QueryEscape(resourceGroupName), @@ -83,11 +86,11 @@ func (client PublicIPAddressesClient) CreateOrUpdatePreparer(resourceGroupName s "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), - autorest.WithPath("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}/"), + autorest.WithPath("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}"), autorest.WithJSON(parameters), autorest.WithPathParameters(pathParameters), autorest.WithQueryParameters(queryParameters)) @@ -96,49 +99,52 @@ func (client PublicIPAddressesClient) CreateOrUpdatePreparer(resourceGroupName s // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client PublicIPAddressesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusCreated, http.StatusOK) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client PublicIPAddressesClient) CreateOrUpdateResponder(resp *http.Response) (result PublicIPAddress, err error) { +func (client PublicIPAddressesClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), - autorest.ByUnmarshallingJSON(&result), + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + result.Response = resp return } // Delete the delete publicIpAddress operation deletes the specified -// publicIpAddress. +// publicIpAddress. This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. publicIPAddressName is // the name of the subnet. -func (client PublicIPAddressesClient) Delete(resourceGroupName string, publicIPAddressName string) (result autorest.Response, ae error) { - req, err := client.DeletePreparer(resourceGroupName, publicIPAddressName) +func (client PublicIPAddressesClient) Delete(resourceGroupName string, publicIPAddressName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, publicIPAddressName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/PublicIPAddressesClient", "Delete", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Delete", nil, "Failure preparing request") } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "network/PublicIPAddressesClient", "Delete", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Delete", resp, "Failure sending request") } result, err = client.DeleteResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/PublicIPAddressesClient", "Delete", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Delete", resp, "Failure responding to request") } return } // DeletePreparer prepares the Delete request. -func (client PublicIPAddressesClient) DeletePreparer(resourceGroupName string, publicIPAddressName string) (*http.Request, error) { +func (client PublicIPAddressesClient) DeletePreparer(resourceGroupName string, publicIPAddressName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "publicIpAddressName": url.QueryEscape(publicIPAddressName), "resourceGroupName": url.QueryEscape(resourceGroupName), @@ -149,11 +155,11 @@ func (client PublicIPAddressesClient) DeletePreparer(resourceGroupName string, p "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), - autorest.WithPath("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}/"), + autorest.WithPath("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}"), autorest.WithPathParameters(pathParameters), autorest.WithQueryParameters(queryParameters)) } @@ -161,7 +167,9 @@ func (client PublicIPAddressesClient) DeletePreparer(resourceGroupName string, p // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client PublicIPAddressesClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusNoContent, http.StatusAccepted, http.StatusOK) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // DeleteResponder handles the response to the Delete request. The method always @@ -170,7 +178,7 @@ func (client PublicIPAddressesClient) DeleteResponder(resp *http.Response) (resu err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusAccepted, http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusAccepted, http.StatusOK), autorest.ByClosing()) result.Response = resp return @@ -181,21 +189,21 @@ func (client PublicIPAddressesClient) DeleteResponder(resp *http.Response) (resu // // resourceGroupName is the name of the resource group. publicIPAddressName is // the name of the subnet. expand is expand references resources. -func (client PublicIPAddressesClient) Get(resourceGroupName string, publicIPAddressName string, expand string) (result PublicIPAddress, ae error) { +func (client PublicIPAddressesClient) Get(resourceGroupName string, publicIPAddressName string, expand string) (result PublicIPAddress, err error) { req, err := client.GetPreparer(resourceGroupName, publicIPAddressName, expand) if err != nil { - return result, autorest.NewErrorWithError(err, "network/PublicIPAddressesClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/PublicIPAddressesClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/PublicIPAddressesClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Get", resp, "Failure responding to request") } return @@ -220,7 +228,7 @@ func (client PublicIPAddressesClient) GetPreparer(resourceGroupName string, publ autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), - autorest.WithPath("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}/"), + autorest.WithPath("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}"), autorest.WithPathParameters(pathParameters), autorest.WithQueryParameters(queryParameters)) } @@ -228,7 +236,7 @@ func (client PublicIPAddressesClient) GetPreparer(resourceGroupName string, publ // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client PublicIPAddressesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -237,7 +245,7 @@ func (client PublicIPAddressesClient) GetResponder(resp *http.Response) (result err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -248,21 +256,21 @@ func (client PublicIPAddressesClient) GetResponder(resp *http.Response) (result // in a resource group. // // resourceGroupName is the name of the resource group. -func (client PublicIPAddressesClient) List(resourceGroupName string) (result PublicIPAddressListResult, ae error) { +func (client PublicIPAddressesClient) List(resourceGroupName string) (result PublicIPAddressListResult, err error) { req, err := client.ListPreparer(resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "network/PublicIPAddressesClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/PublicIPAddressesClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/PublicIPAddressesClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "List", resp, "Failure responding to request") } return @@ -291,7 +299,7 @@ func (client PublicIPAddressesClient) ListPreparer(resourceGroupName string) (*h // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client PublicIPAddressesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -300,7 +308,7 @@ func (client PublicIPAddressesClient) ListResponder(resp *http.Response) (result err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -308,10 +316,10 @@ func (client PublicIPAddressesClient) ListResponder(resp *http.Response) (result } // ListNextResults retrieves the next set of results, if any. -func (client PublicIPAddressesClient) ListNextResults(lastResults PublicIPAddressListResult) (result PublicIPAddressListResult, ae error) { +func (client PublicIPAddressesClient) ListNextResults(lastResults PublicIPAddressListResult) (result PublicIPAddressListResult, err error) { req, err := lastResults.PublicIPAddressListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/PublicIPAddressesClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -320,12 +328,12 @@ func (client PublicIPAddressesClient) ListNextResults(lastResults PublicIPAddres resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/PublicIPAddressesClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/PublicIPAddressesClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "List", resp, "Failure responding to next results request request") } return @@ -333,21 +341,21 @@ func (client PublicIPAddressesClient) ListNextResults(lastResults PublicIPAddres // ListAll the List publicIpAddress opertion retrieves all the // publicIpAddresses in a subscription. -func (client PublicIPAddressesClient) ListAll() (result PublicIPAddressListResult, ae error) { +func (client PublicIPAddressesClient) ListAll() (result PublicIPAddressListResult, err error) { req, err := client.ListAllPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/PublicIPAddressesClient", "ListAll", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListAll", nil, "Failure preparing request") } resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/PublicIPAddressesClient", "ListAll", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListAll", resp, "Failure sending request") } result, err = client.ListAllResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/PublicIPAddressesClient", "ListAll", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListAll", resp, "Failure responding to request") } return @@ -375,7 +383,7 @@ func (client PublicIPAddressesClient) ListAllPreparer() (*http.Request, error) { // ListAllSender sends the ListAll request. The method will close the // http.Response Body if it receives an error. func (client PublicIPAddressesClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListAllResponder handles the response to the ListAll request. The method always @@ -384,7 +392,7 @@ func (client PublicIPAddressesClient) ListAllResponder(resp *http.Response) (res err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -392,10 +400,10 @@ func (client PublicIPAddressesClient) ListAllResponder(resp *http.Response) (res } // ListAllNextResults retrieves the next set of results, if any. -func (client PublicIPAddressesClient) ListAllNextResults(lastResults PublicIPAddressListResult) (result PublicIPAddressListResult, ae error) { +func (client PublicIPAddressesClient) ListAllNextResults(lastResults PublicIPAddressListResult) (result PublicIPAddressListResult, err error) { req, err := lastResults.PublicIPAddressListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/PublicIPAddressesClient", "ListAll", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListAll", nil, "Failure preparing next results request request") } if req == nil { return @@ -404,12 +412,12 @@ func (client PublicIPAddressesClient) ListAllNextResults(lastResults PublicIPAdd resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/PublicIPAddressesClient", "ListAll", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListAll", resp, "Failure sending next results request request") } result, err = client.ListAllResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/PublicIPAddressesClient", "ListAll", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListAll", resp, "Failure responding to next results request request") } return diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/routes.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/routes.go index 751b8a6b21ac..624b26b2770f 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/routes.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/routes.go @@ -14,12 +14,13 @@ package network // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -44,33 +45,35 @@ func NewRoutesClientWithBaseURI(baseURI string, subscriptionID string) RoutesCli } // CreateOrUpdate the Put route operation creates/updates a route in the -// specified route table +// specified route table This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. routeTableName is the // name of the route table. routeName is the name of the route. // routeParameters is parameters supplied to the create/update routeoperation -func (client RoutesClient) CreateOrUpdate(resourceGroupName string, routeTableName string, routeName string, routeParameters Route) (result Route, ae error) { - req, err := client.CreateOrUpdatePreparer(resourceGroupName, routeTableName, routeName, routeParameters) +func (client RoutesClient) CreateOrUpdate(resourceGroupName string, routeTableName string, routeName string, routeParameters Route, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, routeTableName, routeName, routeParameters, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/RoutesClient", "CreateOrUpdate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.RoutesClient", "CreateOrUpdate", nil, "Failure preparing request") } resp, err := client.CreateOrUpdateSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/RoutesClient", "CreateOrUpdate", resp.StatusCode, "Failure sending request") + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.RoutesClient", "CreateOrUpdate", resp, "Failure sending request") } result, err = client.CreateOrUpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/RoutesClient", "CreateOrUpdate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.RoutesClient", "CreateOrUpdate", resp, "Failure responding to request") } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client RoutesClient) CreateOrUpdatePreparer(resourceGroupName string, routeTableName string, routeName string, routeParameters Route) (*http.Request, error) { +func (client RoutesClient) CreateOrUpdatePreparer(resourceGroupName string, routeTableName string, routeName string, routeParameters Route, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "routeName": url.QueryEscape(routeName), @@ -82,7 +85,7 @@ func (client RoutesClient) CreateOrUpdatePreparer(resourceGroupName string, rout "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), @@ -95,49 +98,52 @@ func (client RoutesClient) CreateOrUpdatePreparer(resourceGroupName string, rout // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client RoutesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusCreated) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client RoutesClient) CreateOrUpdateResponder(resp *http.Response) (result Route, err error) { +func (client RoutesClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + result.Response = resp return } // Delete the delete route operation deletes the specified route from a route -// table. +// table. This method may poll for completion. Polling can be canceled by +// passing the cancel channel argument. The channel will be used to cancel +// polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. routeTableName is the // name of the route table. routeName is the name of the route. -func (client RoutesClient) Delete(resourceGroupName string, routeTableName string, routeName string) (result autorest.Response, ae error) { - req, err := client.DeletePreparer(resourceGroupName, routeTableName, routeName) +func (client RoutesClient) Delete(resourceGroupName string, routeTableName string, routeName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, routeTableName, routeName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/RoutesClient", "Delete", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.RoutesClient", "Delete", nil, "Failure preparing request") } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "network/RoutesClient", "Delete", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.RoutesClient", "Delete", resp, "Failure sending request") } result, err = client.DeleteResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/RoutesClient", "Delete", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.RoutesClient", "Delete", resp, "Failure responding to request") } return } // DeletePreparer prepares the Delete request. -func (client RoutesClient) DeletePreparer(resourceGroupName string, routeTableName string, routeName string) (*http.Request, error) { +func (client RoutesClient) DeletePreparer(resourceGroupName string, routeTableName string, routeName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "routeName": url.QueryEscape(routeName), @@ -149,7 +155,7 @@ func (client RoutesClient) DeletePreparer(resourceGroupName string, routeTableNa "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), @@ -161,7 +167,9 @@ func (client RoutesClient) DeletePreparer(resourceGroupName string, routeTableNa // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client RoutesClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusAccepted, http.StatusOK, http.StatusNoContent) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // DeleteResponder handles the response to the Delete request. The method always @@ -170,7 +178,7 @@ func (client RoutesClient) DeleteResponder(resp *http.Response) (result autorest err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusOK, http.StatusNoContent), + azure.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusOK, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return @@ -181,21 +189,21 @@ func (client RoutesClient) DeleteResponder(resp *http.Response) (result autorest // // resourceGroupName is the name of the resource group. routeTableName is the // name of the route table. routeName is the name of the route. -func (client RoutesClient) Get(resourceGroupName string, routeTableName string, routeName string) (result Route, ae error) { +func (client RoutesClient) Get(resourceGroupName string, routeTableName string, routeName string) (result Route, err error) { req, err := client.GetPreparer(resourceGroupName, routeTableName, routeName) if err != nil { - return result, autorest.NewErrorWithError(err, "network/RoutesClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.RoutesClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/RoutesClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.RoutesClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/RoutesClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.RoutesClient", "Get", resp, "Failure responding to request") } return @@ -226,7 +234,7 @@ func (client RoutesClient) GetPreparer(resourceGroupName string, routeTableName // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client RoutesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -235,7 +243,7 @@ func (client RoutesClient) GetResponder(resp *http.Response) (result Route, err err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -247,21 +255,21 @@ func (client RoutesClient) GetResponder(resp *http.Response) (result Route, err // // resourceGroupName is the name of the resource group. routeTableName is the // name of the route table. -func (client RoutesClient) List(resourceGroupName string, routeTableName string) (result RouteListResult, ae error) { +func (client RoutesClient) List(resourceGroupName string, routeTableName string) (result RouteListResult, err error) { req, err := client.ListPreparer(resourceGroupName, routeTableName) if err != nil { - return result, autorest.NewErrorWithError(err, "network/RoutesClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.RoutesClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/RoutesClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.RoutesClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/RoutesClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.RoutesClient", "List", resp, "Failure responding to request") } return @@ -291,7 +299,7 @@ func (client RoutesClient) ListPreparer(resourceGroupName string, routeTableName // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client RoutesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -300,7 +308,7 @@ func (client RoutesClient) ListResponder(resp *http.Response) (result RouteListR err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -308,10 +316,10 @@ func (client RoutesClient) ListResponder(resp *http.Response) (result RouteListR } // ListNextResults retrieves the next set of results, if any. -func (client RoutesClient) ListNextResults(lastResults RouteListResult) (result RouteListResult, ae error) { +func (client RoutesClient) ListNextResults(lastResults RouteListResult) (result RouteListResult, err error) { req, err := lastResults.RouteListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/RoutesClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "network.RoutesClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -320,12 +328,12 @@ func (client RoutesClient) ListNextResults(lastResults RouteListResult) (result resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/RoutesClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "network.RoutesClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/RoutesClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "network.RoutesClient", "List", resp, "Failure responding to next results request request") } return diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/routetables.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/routetables.go index 363e6a5a15a8..9008d4e03789 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/routetables.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/routetables.go @@ -14,12 +14,13 @@ package network // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -45,33 +46,35 @@ func NewRouteTablesClientWithBaseURI(baseURI string, subscriptionID string) Rout } // CreateOrUpdate the Put RouteTable operation creates/updates a route tablein -// the specified resource group. +// the specified resource group. This method may poll for completion. Polling +// can be canceled by passing the cancel channel argument. The channel will +// be used to cancel polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. routeTableName is the // name of the route table. parameters is parameters supplied to the // create/update Route Table operation -func (client RouteTablesClient) CreateOrUpdate(resourceGroupName string, routeTableName string, parameters RouteTable) (result RouteTable, ae error) { - req, err := client.CreateOrUpdatePreparer(resourceGroupName, routeTableName, parameters) +func (client RouteTablesClient) CreateOrUpdate(resourceGroupName string, routeTableName string, parameters RouteTable, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, routeTableName, parameters, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/RouteTablesClient", "CreateOrUpdate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "CreateOrUpdate", nil, "Failure preparing request") } resp, err := client.CreateOrUpdateSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/RouteTablesClient", "CreateOrUpdate", resp.StatusCode, "Failure sending request") + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "CreateOrUpdate", resp, "Failure sending request") } result, err = client.CreateOrUpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/RouteTablesClient", "CreateOrUpdate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "CreateOrUpdate", resp, "Failure responding to request") } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client RouteTablesClient) CreateOrUpdatePreparer(resourceGroupName string, routeTableName string, parameters RouteTable) (*http.Request, error) { +func (client RouteTablesClient) CreateOrUpdatePreparer(resourceGroupName string, routeTableName string, parameters RouteTable, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "routeTableName": url.QueryEscape(routeTableName), @@ -82,7 +85,7 @@ func (client RouteTablesClient) CreateOrUpdatePreparer(resourceGroupName string, "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), @@ -95,48 +98,52 @@ func (client RouteTablesClient) CreateOrUpdatePreparer(resourceGroupName string, // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client RouteTablesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusCreated) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client RouteTablesClient) CreateOrUpdateResponder(resp *http.Response) (result RouteTable, err error) { +func (client RouteTablesClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + result.Response = resp return } // Delete the Delete RouteTable operation deletes the specifed Route Table +// This method may poll for completion. Polling can be canceled by passing +// the cancel channel argument. The channel will be used to cancel polling +// and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. routeTableName is the // name of the route table. -func (client RouteTablesClient) Delete(resourceGroupName string, routeTableName string) (result autorest.Response, ae error) { - req, err := client.DeletePreparer(resourceGroupName, routeTableName) +func (client RouteTablesClient) Delete(resourceGroupName string, routeTableName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, routeTableName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/RouteTablesClient", "Delete", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "Delete", nil, "Failure preparing request") } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "network/RouteTablesClient", "Delete", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "Delete", resp, "Failure sending request") } result, err = client.DeleteResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/RouteTablesClient", "Delete", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "Delete", resp, "Failure responding to request") } return } // DeletePreparer prepares the Delete request. -func (client RouteTablesClient) DeletePreparer(resourceGroupName string, routeTableName string) (*http.Request, error) { +func (client RouteTablesClient) DeletePreparer(resourceGroupName string, routeTableName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "routeTableName": url.QueryEscape(routeTableName), @@ -147,7 +154,7 @@ func (client RouteTablesClient) DeletePreparer(resourceGroupName string, routeTa "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), @@ -159,7 +166,9 @@ func (client RouteTablesClient) DeletePreparer(resourceGroupName string, routeTa // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client RouteTablesClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusNoContent, http.StatusOK, http.StatusAccepted) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // DeleteResponder handles the response to the Delete request. The method always @@ -168,7 +177,7 @@ func (client RouteTablesClient) DeleteResponder(resp *http.Response) (result aut err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusOK, http.StatusAccepted), + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return @@ -179,21 +188,21 @@ func (client RouteTablesClient) DeleteResponder(resp *http.Response) (result aut // // resourceGroupName is the name of the resource group. routeTableName is the // name of the route table. expand is expand references resources. -func (client RouteTablesClient) Get(resourceGroupName string, routeTableName string, expand string) (result RouteTable, ae error) { +func (client RouteTablesClient) Get(resourceGroupName string, routeTableName string, expand string) (result RouteTable, err error) { req, err := client.GetPreparer(resourceGroupName, routeTableName, expand) if err != nil { - return result, autorest.NewErrorWithError(err, "network/RouteTablesClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/RouteTablesClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/RouteTablesClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "Get", resp, "Failure responding to request") } return @@ -226,7 +235,7 @@ func (client RouteTablesClient) GetPreparer(resourceGroupName string, routeTable // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client RouteTablesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -235,7 +244,7 @@ func (client RouteTablesClient) GetResponder(resp *http.Response) (result RouteT err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -245,21 +254,21 @@ func (client RouteTablesClient) GetResponder(resp *http.Response) (result RouteT // List the list RouteTables returns all route tables in a resource group // // resourceGroupName is the name of the resource group. -func (client RouteTablesClient) List(resourceGroupName string) (result RouteTableListResult, ae error) { +func (client RouteTablesClient) List(resourceGroupName string) (result RouteTableListResult, err error) { req, err := client.ListPreparer(resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "network/RouteTablesClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/RouteTablesClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/RouteTablesClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "List", resp, "Failure responding to request") } return @@ -288,7 +297,7 @@ func (client RouteTablesClient) ListPreparer(resourceGroupName string) (*http.Re // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client RouteTablesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -297,7 +306,7 @@ func (client RouteTablesClient) ListResponder(resp *http.Response) (result Route err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -305,10 +314,10 @@ func (client RouteTablesClient) ListResponder(resp *http.Response) (result Route } // ListNextResults retrieves the next set of results, if any. -func (client RouteTablesClient) ListNextResults(lastResults RouteTableListResult) (result RouteTableListResult, ae error) { +func (client RouteTablesClient) ListNextResults(lastResults RouteTableListResult) (result RouteTableListResult, err error) { req, err := lastResults.RouteTableListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/RouteTablesClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -317,33 +326,33 @@ func (client RouteTablesClient) ListNextResults(lastResults RouteTableListResult resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/RouteTablesClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/RouteTablesClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "List", resp, "Failure responding to next results request request") } return } // ListAll the list RouteTables returns all route tables in a subscription -func (client RouteTablesClient) ListAll() (result RouteTableListResult, ae error) { +func (client RouteTablesClient) ListAll() (result RouteTableListResult, err error) { req, err := client.ListAllPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/RouteTablesClient", "ListAll", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "ListAll", nil, "Failure preparing request") } resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/RouteTablesClient", "ListAll", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "ListAll", resp, "Failure sending request") } result, err = client.ListAllResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/RouteTablesClient", "ListAll", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "ListAll", resp, "Failure responding to request") } return @@ -371,7 +380,7 @@ func (client RouteTablesClient) ListAllPreparer() (*http.Request, error) { // ListAllSender sends the ListAll request. The method will close the // http.Response Body if it receives an error. func (client RouteTablesClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListAllResponder handles the response to the ListAll request. The method always @@ -380,7 +389,7 @@ func (client RouteTablesClient) ListAllResponder(resp *http.Response) (result Ro err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -388,10 +397,10 @@ func (client RouteTablesClient) ListAllResponder(resp *http.Response) (result Ro } // ListAllNextResults retrieves the next set of results, if any. -func (client RouteTablesClient) ListAllNextResults(lastResults RouteTableListResult) (result RouteTableListResult, ae error) { +func (client RouteTablesClient) ListAllNextResults(lastResults RouteTableListResult) (result RouteTableListResult, err error) { req, err := lastResults.RouteTableListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/RouteTablesClient", "ListAll", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "ListAll", nil, "Failure preparing next results request request") } if req == nil { return @@ -400,12 +409,12 @@ func (client RouteTablesClient) ListAllNextResults(lastResults RouteTableListRes resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/RouteTablesClient", "ListAll", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "ListAll", resp, "Failure sending next results request request") } result, err = client.ListAllResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/RouteTablesClient", "ListAll", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "ListAll", resp, "Failure responding to next results request request") } return diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/securitygroups.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/securitygroups.go index 1d3b3f176162..0b834af9ea7c 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/securitygroups.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/securitygroups.go @@ -14,12 +14,13 @@ package network // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -46,34 +47,37 @@ func NewSecurityGroupsClientWithBaseURI(baseURI string, subscriptionID string) S } // CreateOrUpdate the Put NetworkSecurityGroup operation creates/updates a -// network security groupin the specified resource group. +// network security groupin the specified resource group. This method may +// poll for completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. // // resourceGroupName is the name of the resource group. // networkSecurityGroupName is the name of the network security group. // parameters is parameters supplied to the create/update Network Security // Group operation -func (client SecurityGroupsClient) CreateOrUpdate(resourceGroupName string, networkSecurityGroupName string, parameters SecurityGroup) (result SecurityGroup, ae error) { - req, err := client.CreateOrUpdatePreparer(resourceGroupName, networkSecurityGroupName, parameters) +func (client SecurityGroupsClient) CreateOrUpdate(resourceGroupName string, networkSecurityGroupName string, parameters SecurityGroup, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, networkSecurityGroupName, parameters, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/SecurityGroupsClient", "CreateOrUpdate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "CreateOrUpdate", nil, "Failure preparing request") } resp, err := client.CreateOrUpdateSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/SecurityGroupsClient", "CreateOrUpdate", resp.StatusCode, "Failure sending request") + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "CreateOrUpdate", resp, "Failure sending request") } result, err = client.CreateOrUpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/SecurityGroupsClient", "CreateOrUpdate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "CreateOrUpdate", resp, "Failure responding to request") } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client SecurityGroupsClient) CreateOrUpdatePreparer(resourceGroupName string, networkSecurityGroupName string, parameters SecurityGroup) (*http.Request, error) { +func (client SecurityGroupsClient) CreateOrUpdatePreparer(resourceGroupName string, networkSecurityGroupName string, parameters SecurityGroup, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "networkSecurityGroupName": url.QueryEscape(networkSecurityGroupName), "resourceGroupName": url.QueryEscape(resourceGroupName), @@ -84,7 +88,7 @@ func (client SecurityGroupsClient) CreateOrUpdatePreparer(resourceGroupName stri "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), @@ -97,49 +101,52 @@ func (client SecurityGroupsClient) CreateOrUpdatePreparer(resourceGroupName stri // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client SecurityGroupsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusCreated, http.StatusOK) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client SecurityGroupsClient) CreateOrUpdateResponder(resp *http.Response) (result SecurityGroup, err error) { +func (client SecurityGroupsClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), - autorest.ByUnmarshallingJSON(&result), + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + result.Response = resp return } // Delete the Delete NetworkSecurityGroup operation deletes the specifed -// network security group +// network security group This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. // networkSecurityGroupName is the name of the network security group. -func (client SecurityGroupsClient) Delete(resourceGroupName string, networkSecurityGroupName string) (result autorest.Response, ae error) { - req, err := client.DeletePreparer(resourceGroupName, networkSecurityGroupName) +func (client SecurityGroupsClient) Delete(resourceGroupName string, networkSecurityGroupName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, networkSecurityGroupName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/SecurityGroupsClient", "Delete", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Delete", nil, "Failure preparing request") } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "network/SecurityGroupsClient", "Delete", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Delete", resp, "Failure sending request") } result, err = client.DeleteResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/SecurityGroupsClient", "Delete", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Delete", resp, "Failure responding to request") } return } // DeletePreparer prepares the Delete request. -func (client SecurityGroupsClient) DeletePreparer(resourceGroupName string, networkSecurityGroupName string) (*http.Request, error) { +func (client SecurityGroupsClient) DeletePreparer(resourceGroupName string, networkSecurityGroupName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "networkSecurityGroupName": url.QueryEscape(networkSecurityGroupName), "resourceGroupName": url.QueryEscape(resourceGroupName), @@ -150,7 +157,7 @@ func (client SecurityGroupsClient) DeletePreparer(resourceGroupName string, netw "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), @@ -162,7 +169,9 @@ func (client SecurityGroupsClient) DeletePreparer(resourceGroupName string, netw // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client SecurityGroupsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusAccepted, http.StatusOK, http.StatusNoContent) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // DeleteResponder handles the response to the Delete request. The method always @@ -171,7 +180,7 @@ func (client SecurityGroupsClient) DeleteResponder(resp *http.Response) (result err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusOK, http.StatusNoContent), + azure.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusOK, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return @@ -183,21 +192,21 @@ func (client SecurityGroupsClient) DeleteResponder(resp *http.Response) (result // resourceGroupName is the name of the resource group. // networkSecurityGroupName is the name of the network security group. expand // is expand references resources. -func (client SecurityGroupsClient) Get(resourceGroupName string, networkSecurityGroupName string, expand string) (result SecurityGroup, ae error) { +func (client SecurityGroupsClient) Get(resourceGroupName string, networkSecurityGroupName string, expand string) (result SecurityGroup, err error) { req, err := client.GetPreparer(resourceGroupName, networkSecurityGroupName, expand) if err != nil { - return result, autorest.NewErrorWithError(err, "network/SecurityGroupsClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/SecurityGroupsClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/SecurityGroupsClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Get", resp, "Failure responding to request") } return @@ -230,7 +239,7 @@ func (client SecurityGroupsClient) GetPreparer(resourceGroupName string, network // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client SecurityGroupsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -239,7 +248,7 @@ func (client SecurityGroupsClient) GetResponder(resp *http.Response) (result Sec err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -250,21 +259,21 @@ func (client SecurityGroupsClient) GetResponder(resp *http.Response) (result Sec // a resource group // // resourceGroupName is the name of the resource group. -func (client SecurityGroupsClient) List(resourceGroupName string) (result SecurityGroupListResult, ae error) { +func (client SecurityGroupsClient) List(resourceGroupName string) (result SecurityGroupListResult, err error) { req, err := client.ListPreparer(resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "network/SecurityGroupsClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/SecurityGroupsClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/SecurityGroupsClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "List", resp, "Failure responding to request") } return @@ -293,7 +302,7 @@ func (client SecurityGroupsClient) ListPreparer(resourceGroupName string) (*http // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client SecurityGroupsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -302,7 +311,7 @@ func (client SecurityGroupsClient) ListResponder(resp *http.Response) (result Se err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -310,10 +319,10 @@ func (client SecurityGroupsClient) ListResponder(resp *http.Response) (result Se } // ListNextResults retrieves the next set of results, if any. -func (client SecurityGroupsClient) ListNextResults(lastResults SecurityGroupListResult) (result SecurityGroupListResult, ae error) { +func (client SecurityGroupsClient) ListNextResults(lastResults SecurityGroupListResult) (result SecurityGroupListResult, err error) { req, err := lastResults.SecurityGroupListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/SecurityGroupsClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -322,12 +331,12 @@ func (client SecurityGroupsClient) ListNextResults(lastResults SecurityGroupList resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/SecurityGroupsClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/SecurityGroupsClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "List", resp, "Failure responding to next results request request") } return @@ -335,21 +344,21 @@ func (client SecurityGroupsClient) ListNextResults(lastResults SecurityGroupList // ListAll the list NetworkSecurityGroups returns all network security groups // in a subscription -func (client SecurityGroupsClient) ListAll() (result SecurityGroupListResult, ae error) { +func (client SecurityGroupsClient) ListAll() (result SecurityGroupListResult, err error) { req, err := client.ListAllPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/SecurityGroupsClient", "ListAll", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "ListAll", nil, "Failure preparing request") } resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/SecurityGroupsClient", "ListAll", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "ListAll", resp, "Failure sending request") } result, err = client.ListAllResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/SecurityGroupsClient", "ListAll", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "ListAll", resp, "Failure responding to request") } return @@ -377,7 +386,7 @@ func (client SecurityGroupsClient) ListAllPreparer() (*http.Request, error) { // ListAllSender sends the ListAll request. The method will close the // http.Response Body if it receives an error. func (client SecurityGroupsClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListAllResponder handles the response to the ListAll request. The method always @@ -386,7 +395,7 @@ func (client SecurityGroupsClient) ListAllResponder(resp *http.Response) (result err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -394,10 +403,10 @@ func (client SecurityGroupsClient) ListAllResponder(resp *http.Response) (result } // ListAllNextResults retrieves the next set of results, if any. -func (client SecurityGroupsClient) ListAllNextResults(lastResults SecurityGroupListResult) (result SecurityGroupListResult, ae error) { +func (client SecurityGroupsClient) ListAllNextResults(lastResults SecurityGroupListResult) (result SecurityGroupListResult, err error) { req, err := lastResults.SecurityGroupListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/SecurityGroupsClient", "ListAll", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "ListAll", nil, "Failure preparing next results request request") } if req == nil { return @@ -406,12 +415,12 @@ func (client SecurityGroupsClient) ListAllNextResults(lastResults SecurityGroupL resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/SecurityGroupsClient", "ListAll", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "ListAll", resp, "Failure sending next results request request") } result, err = client.ListAllResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/SecurityGroupsClient", "ListAll", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "ListAll", resp, "Failure responding to next results request request") } return diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/securityrules.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/securityrules.go index b009f04396fa..8cf5e3cc6c54 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/securityrules.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/securityrules.go @@ -14,12 +14,13 @@ package network // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -46,35 +47,38 @@ func NewSecurityRulesClientWithBaseURI(baseURI string, subscriptionID string) Se } // CreateOrUpdate the Put network security rule operation creates/updates a -// security rule in the specified network security group +// security rule in the specified network security group This method may poll +// for completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. // // resourceGroupName is the name of the resource group. // networkSecurityGroupName is the name of the network security group. // securityRuleName is the name of the security rule. securityRuleParameters // is parameters supplied to the create/update network security rule // operation -func (client SecurityRulesClient) CreateOrUpdate(resourceGroupName string, networkSecurityGroupName string, securityRuleName string, securityRuleParameters SecurityRule) (result SecurityRule, ae error) { - req, err := client.CreateOrUpdatePreparer(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters) +func (client SecurityRulesClient) CreateOrUpdate(resourceGroupName string, networkSecurityGroupName string, securityRuleName string, securityRuleParameters SecurityRule, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/SecurityRulesClient", "CreateOrUpdate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.SecurityRulesClient", "CreateOrUpdate", nil, "Failure preparing request") } resp, err := client.CreateOrUpdateSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/SecurityRulesClient", "CreateOrUpdate", resp.StatusCode, "Failure sending request") + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.SecurityRulesClient", "CreateOrUpdate", resp, "Failure sending request") } result, err = client.CreateOrUpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/SecurityRulesClient", "CreateOrUpdate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "CreateOrUpdate", resp, "Failure responding to request") } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client SecurityRulesClient) CreateOrUpdatePreparer(resourceGroupName string, networkSecurityGroupName string, securityRuleName string, securityRuleParameters SecurityRule) (*http.Request, error) { +func (client SecurityRulesClient) CreateOrUpdatePreparer(resourceGroupName string, networkSecurityGroupName string, securityRuleName string, securityRuleParameters SecurityRule, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "networkSecurityGroupName": url.QueryEscape(networkSecurityGroupName), "resourceGroupName": url.QueryEscape(resourceGroupName), @@ -86,7 +90,7 @@ func (client SecurityRulesClient) CreateOrUpdatePreparer(resourceGroupName strin "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), @@ -99,50 +103,53 @@ func (client SecurityRulesClient) CreateOrUpdatePreparer(resourceGroupName strin // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client SecurityRulesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusCreated) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client SecurityRulesClient) CreateOrUpdateResponder(resp *http.Response) (result SecurityRule, err error) { +func (client SecurityRulesClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + result.Response = resp return } // Delete the delete network security rule operation deletes the specified -// network security rule. +// network security rule. This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. // networkSecurityGroupName is the name of the network security group. // securityRuleName is the name of the security rule. -func (client SecurityRulesClient) Delete(resourceGroupName string, networkSecurityGroupName string, securityRuleName string) (result autorest.Response, ae error) { - req, err := client.DeletePreparer(resourceGroupName, networkSecurityGroupName, securityRuleName) +func (client SecurityRulesClient) Delete(resourceGroupName string, networkSecurityGroupName string, securityRuleName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, networkSecurityGroupName, securityRuleName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/SecurityRulesClient", "Delete", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.SecurityRulesClient", "Delete", nil, "Failure preparing request") } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "network/SecurityRulesClient", "Delete", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.SecurityRulesClient", "Delete", resp, "Failure sending request") } result, err = client.DeleteResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/SecurityRulesClient", "Delete", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "Delete", resp, "Failure responding to request") } return } // DeletePreparer prepares the Delete request. -func (client SecurityRulesClient) DeletePreparer(resourceGroupName string, networkSecurityGroupName string, securityRuleName string) (*http.Request, error) { +func (client SecurityRulesClient) DeletePreparer(resourceGroupName string, networkSecurityGroupName string, securityRuleName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "networkSecurityGroupName": url.QueryEscape(networkSecurityGroupName), "resourceGroupName": url.QueryEscape(resourceGroupName), @@ -154,7 +161,7 @@ func (client SecurityRulesClient) DeletePreparer(resourceGroupName string, netwo "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), @@ -166,7 +173,9 @@ func (client SecurityRulesClient) DeletePreparer(resourceGroupName string, netwo // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client SecurityRulesClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusNoContent, http.StatusAccepted, http.StatusOK) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // DeleteResponder handles the response to the Delete request. The method always @@ -175,7 +184,7 @@ func (client SecurityRulesClient) DeleteResponder(resp *http.Response) (result a err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusAccepted, http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusAccepted, http.StatusOK), autorest.ByClosing()) result.Response = resp return @@ -187,21 +196,21 @@ func (client SecurityRulesClient) DeleteResponder(resp *http.Response) (result a // resourceGroupName is the name of the resource group. // networkSecurityGroupName is the name of the network security group. // securityRuleName is the name of the security rule. -func (client SecurityRulesClient) Get(resourceGroupName string, networkSecurityGroupName string, securityRuleName string) (result SecurityRule, ae error) { +func (client SecurityRulesClient) Get(resourceGroupName string, networkSecurityGroupName string, securityRuleName string) (result SecurityRule, err error) { req, err := client.GetPreparer(resourceGroupName, networkSecurityGroupName, securityRuleName) if err != nil { - return result, autorest.NewErrorWithError(err, "network/SecurityRulesClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.SecurityRulesClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/SecurityRulesClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.SecurityRulesClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/SecurityRulesClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "Get", resp, "Failure responding to request") } return @@ -232,7 +241,7 @@ func (client SecurityRulesClient) GetPreparer(resourceGroupName string, networkS // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client SecurityRulesClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -241,7 +250,7 @@ func (client SecurityRulesClient) GetResponder(resp *http.Response) (result Secu err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -253,21 +262,21 @@ func (client SecurityRulesClient) GetResponder(resp *http.Response) (result Secu // // resourceGroupName is the name of the resource group. // networkSecurityGroupName is the name of the network security group. -func (client SecurityRulesClient) List(resourceGroupName string, networkSecurityGroupName string) (result SecurityRuleListResult, ae error) { +func (client SecurityRulesClient) List(resourceGroupName string, networkSecurityGroupName string) (result SecurityRuleListResult, err error) { req, err := client.ListPreparer(resourceGroupName, networkSecurityGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "network/SecurityRulesClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.SecurityRulesClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/SecurityRulesClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.SecurityRulesClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/SecurityRulesClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "List", resp, "Failure responding to request") } return @@ -297,7 +306,7 @@ func (client SecurityRulesClient) ListPreparer(resourceGroupName string, network // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client SecurityRulesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -306,7 +315,7 @@ func (client SecurityRulesClient) ListResponder(resp *http.Response) (result Sec err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -314,10 +323,10 @@ func (client SecurityRulesClient) ListResponder(resp *http.Response) (result Sec } // ListNextResults retrieves the next set of results, if any. -func (client SecurityRulesClient) ListNextResults(lastResults SecurityRuleListResult) (result SecurityRuleListResult, ae error) { +func (client SecurityRulesClient) ListNextResults(lastResults SecurityRuleListResult) (result SecurityRuleListResult, err error) { req, err := lastResults.SecurityRuleListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/SecurityRulesClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "network.SecurityRulesClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -326,12 +335,12 @@ func (client SecurityRulesClient) ListNextResults(lastResults SecurityRuleListRe resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/SecurityRulesClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "network.SecurityRulesClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/SecurityRulesClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "List", resp, "Failure responding to next results request request") } return diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/subnets.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/subnets.go index 94ecf759d087..1c75a2760fe1 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/subnets.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/subnets.go @@ -14,12 +14,13 @@ package network // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -44,34 +45,36 @@ func NewSubnetsClientWithBaseURI(baseURI string, subscriptionID string) SubnetsC } // CreateOrUpdate the Put Subnet operation creates/updates a subnet in -// thespecified virtual network +// thespecified virtual network This method may poll for completion. Polling +// can be canceled by passing the cancel channel argument. The channel will +// be used to cancel polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. virtualNetworkName is // the name of the virtual network. subnetName is the name of the subnet. // subnetParameters is parameters supplied to the create/update Subnet // operation -func (client SubnetsClient) CreateOrUpdate(resourceGroupName string, virtualNetworkName string, subnetName string, subnetParameters Subnet) (result Subnet, ae error) { - req, err := client.CreateOrUpdatePreparer(resourceGroupName, virtualNetworkName, subnetName, subnetParameters) +func (client SubnetsClient) CreateOrUpdate(resourceGroupName string, virtualNetworkName string, subnetName string, subnetParameters Subnet, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, virtualNetworkName, subnetName, subnetParameters, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/SubnetsClient", "CreateOrUpdate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.SubnetsClient", "CreateOrUpdate", nil, "Failure preparing request") } resp, err := client.CreateOrUpdateSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/SubnetsClient", "CreateOrUpdate", resp.StatusCode, "Failure sending request") + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.SubnetsClient", "CreateOrUpdate", resp, "Failure sending request") } result, err = client.CreateOrUpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/SubnetsClient", "CreateOrUpdate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.SubnetsClient", "CreateOrUpdate", resp, "Failure responding to request") } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client SubnetsClient) CreateOrUpdatePreparer(resourceGroupName string, virtualNetworkName string, subnetName string, subnetParameters Subnet) (*http.Request, error) { +func (client SubnetsClient) CreateOrUpdatePreparer(resourceGroupName string, virtualNetworkName string, subnetName string, subnetParameters Subnet, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "subnetName": url.QueryEscape(subnetName), @@ -83,7 +86,7 @@ func (client SubnetsClient) CreateOrUpdatePreparer(resourceGroupName string, vir "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), @@ -96,48 +99,52 @@ func (client SubnetsClient) CreateOrUpdatePreparer(resourceGroupName string, vir // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client SubnetsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusCreated) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client SubnetsClient) CreateOrUpdateResponder(resp *http.Response) (result Subnet, err error) { +func (client SubnetsClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + result.Response = resp return } -// Delete the delete subnet operation deletes the specified subnet. +// Delete the delete subnet operation deletes the specified subnet. This +// method may poll for completion. Polling can be canceled by passing the +// cancel channel argument. The channel will be used to cancel polling and +// any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. virtualNetworkName is // the name of the virtual network. subnetName is the name of the subnet. -func (client SubnetsClient) Delete(resourceGroupName string, virtualNetworkName string, subnetName string) (result autorest.Response, ae error) { - req, err := client.DeletePreparer(resourceGroupName, virtualNetworkName, subnetName) +func (client SubnetsClient) Delete(resourceGroupName string, virtualNetworkName string, subnetName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, virtualNetworkName, subnetName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/SubnetsClient", "Delete", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.SubnetsClient", "Delete", nil, "Failure preparing request") } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "network/SubnetsClient", "Delete", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.SubnetsClient", "Delete", resp, "Failure sending request") } result, err = client.DeleteResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/SubnetsClient", "Delete", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.SubnetsClient", "Delete", resp, "Failure responding to request") } return } // DeletePreparer prepares the Delete request. -func (client SubnetsClient) DeletePreparer(resourceGroupName string, virtualNetworkName string, subnetName string) (*http.Request, error) { +func (client SubnetsClient) DeletePreparer(resourceGroupName string, virtualNetworkName string, subnetName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "subnetName": url.QueryEscape(subnetName), @@ -149,7 +156,7 @@ func (client SubnetsClient) DeletePreparer(resourceGroupName string, virtualNetw "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), @@ -161,7 +168,9 @@ func (client SubnetsClient) DeletePreparer(resourceGroupName string, virtualNetw // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client SubnetsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusNoContent, http.StatusAccepted) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // DeleteResponder handles the response to the Delete request. The method always @@ -170,7 +179,7 @@ func (client SubnetsClient) DeleteResponder(resp *http.Response) (result autores err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent, http.StatusAccepted), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return @@ -182,21 +191,21 @@ func (client SubnetsClient) DeleteResponder(resp *http.Response) (result autores // resourceGroupName is the name of the resource group. virtualNetworkName is // the name of the virtual network. subnetName is the name of the subnet. // expand is expand references resources. -func (client SubnetsClient) Get(resourceGroupName string, virtualNetworkName string, subnetName string, expand string) (result Subnet, ae error) { +func (client SubnetsClient) Get(resourceGroupName string, virtualNetworkName string, subnetName string, expand string) (result Subnet, err error) { req, err := client.GetPreparer(resourceGroupName, virtualNetworkName, subnetName, expand) if err != nil { - return result, autorest.NewErrorWithError(err, "network/SubnetsClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.SubnetsClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/SubnetsClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.SubnetsClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/SubnetsClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.SubnetsClient", "Get", resp, "Failure responding to request") } return @@ -230,7 +239,7 @@ func (client SubnetsClient) GetPreparer(resourceGroupName string, virtualNetwork // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client SubnetsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -239,7 +248,7 @@ func (client SubnetsClient) GetResponder(resp *http.Response) (result Subnet, er err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -251,21 +260,21 @@ func (client SubnetsClient) GetResponder(resp *http.Response) (result Subnet, er // // resourceGroupName is the name of the resource group. virtualNetworkName is // the name of the virtual network. -func (client SubnetsClient) List(resourceGroupName string, virtualNetworkName string) (result SubnetListResult, ae error) { +func (client SubnetsClient) List(resourceGroupName string, virtualNetworkName string) (result SubnetListResult, err error) { req, err := client.ListPreparer(resourceGroupName, virtualNetworkName) if err != nil { - return result, autorest.NewErrorWithError(err, "network/SubnetsClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.SubnetsClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/SubnetsClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.SubnetsClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/SubnetsClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.SubnetsClient", "List", resp, "Failure responding to request") } return @@ -295,7 +304,7 @@ func (client SubnetsClient) ListPreparer(resourceGroupName string, virtualNetwor // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client SubnetsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -304,7 +313,7 @@ func (client SubnetsClient) ListResponder(resp *http.Response) (result SubnetLis err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -312,10 +321,10 @@ func (client SubnetsClient) ListResponder(resp *http.Response) (result SubnetLis } // ListNextResults retrieves the next set of results, if any. -func (client SubnetsClient) ListNextResults(lastResults SubnetListResult) (result SubnetListResult, ae error) { +func (client SubnetsClient) ListNextResults(lastResults SubnetListResult) (result SubnetListResult, err error) { req, err := lastResults.SubnetListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/SubnetsClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "network.SubnetsClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -324,12 +333,12 @@ func (client SubnetsClient) ListNextResults(lastResults SubnetListResult) (resul resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/SubnetsClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "network.SubnetsClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/SubnetsClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "network.SubnetsClient", "List", resp, "Failure responding to next results request request") } return diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/usages.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/usages.go index f3a536533ed0..3b2236cafbca 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/usages.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/usages.go @@ -14,12 +14,13 @@ package network // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -46,21 +47,21 @@ func NewUsagesClientWithBaseURI(baseURI string, subscriptionID string) UsagesCli // List lists compute usages for a subscription. // // location is the location upon which resource usage is queried. -func (client UsagesClient) List(location string) (result UsagesListResult, ae error) { +func (client UsagesClient) List(location string) (result UsagesListResult, err error) { req, err := client.ListPreparer(location) if err != nil { - return result, autorest.NewErrorWithError(err, "network/UsagesClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.UsagesClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/UsagesClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.UsagesClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/UsagesClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.UsagesClient", "List", resp, "Failure responding to request") } return @@ -89,7 +90,7 @@ func (client UsagesClient) ListPreparer(location string) (*http.Request, error) // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client UsagesClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -98,7 +99,7 @@ func (client UsagesClient) ListResponder(resp *http.Response) (result UsagesList err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -106,10 +107,10 @@ func (client UsagesClient) ListResponder(resp *http.Response) (result UsagesList } // ListNextResults retrieves the next set of results, if any. -func (client UsagesClient) ListNextResults(lastResults UsagesListResult) (result UsagesListResult, ae error) { +func (client UsagesClient) ListNextResults(lastResults UsagesListResult) (result UsagesListResult, err error) { req, err := lastResults.UsagesListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/UsagesClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "network.UsagesClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -118,12 +119,12 @@ func (client UsagesClient) ListNextResults(lastResults UsagesListResult) (result resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/UsagesClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "network.UsagesClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/UsagesClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "network.UsagesClient", "List", resp, "Failure responding to next results request request") } return diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/version.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/version.go index 2ebbc3b3743c..16e3c74f0928 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/version.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/version.go @@ -14,7 +14,7 @@ package network // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -23,13 +23,13 @@ import ( ) const ( - major = "0" - minor = "4" - patch = "0" + major = "2" + minor = "1" + patch = "1" // Always begin a "tag" with a dash (as per http://semver.org) tag = "-beta" semVerFormat = "%s.%s.%s%s" - userAgentFormat = "Azure-SDK-for-Go/%s;Package arm/%s;API %s" + userAgentFormat = "Azure-SDK-for-Go/%s arm-%s/%s" ) // UserAgent returns the UserAgent string to use when sending http.Requests. diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/virtualnetworkgatewayconnections.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/virtualnetworkgatewayconnections.go index 50fed8751acc..2094cb2e0ed9 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/virtualnetworkgatewayconnections.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/virtualnetworkgatewayconnections.go @@ -14,12 +14,13 @@ package network // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -47,35 +48,38 @@ func NewVirtualNetworkGatewayConnectionsClientWithBaseURI(baseURI string, subscr // CreateOrUpdate the Put VirtualNetworkGatewayConnection operation // creates/updates a virtual network gateway connection in the specified -// resource group through Network resource provider. +// resource group through Network resource provider. This method may poll for +// completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. // // resourceGroupName is the name of the resource group. // virtualNetworkGatewayConnectionName is the name of the virtual network // gateway conenction. parameters is parameters supplied to the Begin Create // or update Virtual Network Gateway connection operation through Network // resource provider. -func (client VirtualNetworkGatewayConnectionsClient) CreateOrUpdate(resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters VirtualNetworkGatewayConnection) (result VirtualNetworkGatewayConnection, ae error) { - req, err := client.CreateOrUpdatePreparer(resourceGroupName, virtualNetworkGatewayConnectionName, parameters) +func (client VirtualNetworkGatewayConnectionsClient) CreateOrUpdate(resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters VirtualNetworkGatewayConnection, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/VirtualNetworkGatewayConnectionsClient", "CreateOrUpdate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "CreateOrUpdate", nil, "Failure preparing request") } resp, err := client.CreateOrUpdateSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/VirtualNetworkGatewayConnectionsClient", "CreateOrUpdate", resp.StatusCode, "Failure sending request") + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "CreateOrUpdate", resp, "Failure sending request") } result, err = client.CreateOrUpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/VirtualNetworkGatewayConnectionsClient", "CreateOrUpdate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "CreateOrUpdate", resp, "Failure responding to request") } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualNetworkGatewayConnectionsClient) CreateOrUpdatePreparer(resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters VirtualNetworkGatewayConnection) (*http.Request, error) { +func (client VirtualNetworkGatewayConnectionsClient) CreateOrUpdatePreparer(resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters VirtualNetworkGatewayConnection, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "subscriptionId": url.QueryEscape(client.SubscriptionID), @@ -86,7 +90,7 @@ func (client VirtualNetworkGatewayConnectionsClient) CreateOrUpdatePreparer(reso "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), @@ -99,51 +103,54 @@ func (client VirtualNetworkGatewayConnectionsClient) CreateOrUpdatePreparer(reso // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client VirtualNetworkGatewayConnectionsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusCreated) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client VirtualNetworkGatewayConnectionsClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualNetworkGatewayConnection, err error) { +func (client VirtualNetworkGatewayConnectionsClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + result.Response = resp return } // Delete the Delete VirtualNetworkGatewayConnection operation deletes the // specifed virtual network Gateway connection through Network resource -// provider. +// provider. This method may poll for completion. Polling can be canceled by +// passing the cancel channel argument. The channel will be used to cancel +// polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. // virtualNetworkGatewayConnectionName is the name of the virtual network // gateway connection. -func (client VirtualNetworkGatewayConnectionsClient) Delete(resourceGroupName string, virtualNetworkGatewayConnectionName string) (result autorest.Response, ae error) { - req, err := client.DeletePreparer(resourceGroupName, virtualNetworkGatewayConnectionName) +func (client VirtualNetworkGatewayConnectionsClient) Delete(resourceGroupName string, virtualNetworkGatewayConnectionName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, virtualNetworkGatewayConnectionName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/VirtualNetworkGatewayConnectionsClient", "Delete", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "Delete", nil, "Failure preparing request") } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "network/VirtualNetworkGatewayConnectionsClient", "Delete", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "Delete", resp, "Failure sending request") } result, err = client.DeleteResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/VirtualNetworkGatewayConnectionsClient", "Delete", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "Delete", resp, "Failure responding to request") } return } // DeletePreparer prepares the Delete request. -func (client VirtualNetworkGatewayConnectionsClient) DeletePreparer(resourceGroupName string, virtualNetworkGatewayConnectionName string) (*http.Request, error) { +func (client VirtualNetworkGatewayConnectionsClient) DeletePreparer(resourceGroupName string, virtualNetworkGatewayConnectionName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "subscriptionId": url.QueryEscape(client.SubscriptionID), @@ -154,11 +161,11 @@ func (client VirtualNetworkGatewayConnectionsClient) DeletePreparer(resourceGrou "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), - autorest.WithPath("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/"), + autorest.WithPath("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}"), autorest.WithPathParameters(pathParameters), autorest.WithQueryParameters(queryParameters)) } @@ -166,7 +173,9 @@ func (client VirtualNetworkGatewayConnectionsClient) DeletePreparer(resourceGrou // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client VirtualNetworkGatewayConnectionsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted, http.StatusNoContent) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // DeleteResponder handles the response to the Delete request. The method always @@ -175,7 +184,7 @@ func (client VirtualNetworkGatewayConnectionsClient) DeleteResponder(resp *http. err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return @@ -188,21 +197,21 @@ func (client VirtualNetworkGatewayConnectionsClient) DeleteResponder(resp *http. // resourceGroupName is the name of the resource group. // virtualNetworkGatewayConnectionName is the name of the virtual network // gateway connection. -func (client VirtualNetworkGatewayConnectionsClient) Get(resourceGroupName string, virtualNetworkGatewayConnectionName string) (result VirtualNetworkGatewayConnection, ae error) { +func (client VirtualNetworkGatewayConnectionsClient) Get(resourceGroupName string, virtualNetworkGatewayConnectionName string) (result VirtualNetworkGatewayConnection, err error) { req, err := client.GetPreparer(resourceGroupName, virtualNetworkGatewayConnectionName) if err != nil { - return result, autorest.NewErrorWithError(err, "network/VirtualNetworkGatewayConnectionsClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/VirtualNetworkGatewayConnectionsClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/VirtualNetworkGatewayConnectionsClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "Get", resp, "Failure responding to request") } return @@ -232,7 +241,7 @@ func (client VirtualNetworkGatewayConnectionsClient) GetPreparer(resourceGroupNa // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client VirtualNetworkGatewayConnectionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -241,7 +250,7 @@ func (client VirtualNetworkGatewayConnectionsClient) GetResponder(resp *http.Res err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -255,21 +264,21 @@ func (client VirtualNetworkGatewayConnectionsClient) GetResponder(resp *http.Res // resourceGroupName is the name of the resource group. // connectionSharedKeyName is the virtual network gateway connection shared // key name. -func (client VirtualNetworkGatewayConnectionsClient) GetSharedKey(resourceGroupName string, connectionSharedKeyName string) (result ConnectionSharedKeyResult, ae error) { +func (client VirtualNetworkGatewayConnectionsClient) GetSharedKey(resourceGroupName string, connectionSharedKeyName string) (result ConnectionSharedKeyResult, err error) { req, err := client.GetSharedKeyPreparer(resourceGroupName, connectionSharedKeyName) if err != nil { - return result, autorest.NewErrorWithError(err, "network/VirtualNetworkGatewayConnectionsClient", "GetSharedKey", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "GetSharedKey", nil, "Failure preparing request") } resp, err := client.GetSharedKeySender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/VirtualNetworkGatewayConnectionsClient", "GetSharedKey", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "GetSharedKey", resp, "Failure sending request") } result, err = client.GetSharedKeyResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/VirtualNetworkGatewayConnectionsClient", "GetSharedKey", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "GetSharedKey", resp, "Failure responding to request") } return @@ -299,7 +308,7 @@ func (client VirtualNetworkGatewayConnectionsClient) GetSharedKeyPreparer(resour // GetSharedKeySender sends the GetSharedKey request. The method will close the // http.Response Body if it receives an error. func (client VirtualNetworkGatewayConnectionsClient) GetSharedKeySender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetSharedKeyResponder handles the response to the GetSharedKey request. The method always @@ -308,7 +317,7 @@ func (client VirtualNetworkGatewayConnectionsClient) GetSharedKeyResponder(resp err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -319,21 +328,21 @@ func (client VirtualNetworkGatewayConnectionsClient) GetSharedKeyResponder(resp // virtual network gateways connections created. // // resourceGroupName is the name of the resource group. -func (client VirtualNetworkGatewayConnectionsClient) List(resourceGroupName string) (result VirtualNetworkGatewayConnectionListResult, ae error) { +func (client VirtualNetworkGatewayConnectionsClient) List(resourceGroupName string) (result VirtualNetworkGatewayConnectionListResult, err error) { req, err := client.ListPreparer(resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "network/VirtualNetworkGatewayConnectionsClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/VirtualNetworkGatewayConnectionsClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/VirtualNetworkGatewayConnectionsClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "List", resp, "Failure responding to request") } return @@ -362,7 +371,7 @@ func (client VirtualNetworkGatewayConnectionsClient) ListPreparer(resourceGroupN // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client VirtualNetworkGatewayConnectionsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -371,7 +380,7 @@ func (client VirtualNetworkGatewayConnectionsClient) ListResponder(resp *http.Re err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -379,10 +388,10 @@ func (client VirtualNetworkGatewayConnectionsClient) ListResponder(resp *http.Re } // ListNextResults retrieves the next set of results, if any. -func (client VirtualNetworkGatewayConnectionsClient) ListNextResults(lastResults VirtualNetworkGatewayConnectionListResult) (result VirtualNetworkGatewayConnectionListResult, ae error) { +func (client VirtualNetworkGatewayConnectionsClient) ListNextResults(lastResults VirtualNetworkGatewayConnectionListResult) (result VirtualNetworkGatewayConnectionListResult, err error) { req, err := lastResults.VirtualNetworkGatewayConnectionListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/VirtualNetworkGatewayConnectionsClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -391,12 +400,12 @@ func (client VirtualNetworkGatewayConnectionsClient) ListNextResults(lastResults resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/VirtualNetworkGatewayConnectionsClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/VirtualNetworkGatewayConnectionsClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "List", resp, "Failure responding to next results request request") } return @@ -405,35 +414,37 @@ func (client VirtualNetworkGatewayConnectionsClient) ListNextResults(lastResults // ResetSharedKey the VirtualNetworkGatewayConnectionResetSharedKey operation // resets the virtual network gateway connection shared key for passed // virtual network gateway connection in the specified resource group through -// Network resource provider. +// Network resource provider. This method may poll for completion. Polling +// can be canceled by passing the cancel channel argument. The channel will +// be used to cancel polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. // virtualNetworkGatewayConnectionName is the virtual network gateway // connection reset shared key Name. parameters is parameters supplied to the // Begin Reset Virtual Network Gateway connection shared key operation // through Network resource provider. -func (client VirtualNetworkGatewayConnectionsClient) ResetSharedKey(resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters ConnectionResetSharedKey) (result ConnectionResetSharedKey, ae error) { - req, err := client.ResetSharedKeyPreparer(resourceGroupName, virtualNetworkGatewayConnectionName, parameters) +func (client VirtualNetworkGatewayConnectionsClient) ResetSharedKey(resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters ConnectionResetSharedKey, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.ResetSharedKeyPreparer(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/VirtualNetworkGatewayConnectionsClient", "ResetSharedKey", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "ResetSharedKey", nil, "Failure preparing request") } resp, err := client.ResetSharedKeySender(req) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/VirtualNetworkGatewayConnectionsClient", "ResetSharedKey", resp.StatusCode, "Failure sending request") + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "ResetSharedKey", resp, "Failure sending request") } result, err = client.ResetSharedKeyResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/VirtualNetworkGatewayConnectionsClient", "ResetSharedKey", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "ResetSharedKey", resp, "Failure responding to request") } return } // ResetSharedKeyPreparer prepares the ResetSharedKey request. -func (client VirtualNetworkGatewayConnectionsClient) ResetSharedKeyPreparer(resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters ConnectionResetSharedKey) (*http.Request, error) { +func (client VirtualNetworkGatewayConnectionsClient) ResetSharedKeyPreparer(resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters ConnectionResetSharedKey, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "subscriptionId": url.QueryEscape(client.SubscriptionID), @@ -444,7 +455,7 @@ func (client VirtualNetworkGatewayConnectionsClient) ResetSharedKeyPreparer(reso "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), @@ -457,54 +468,57 @@ func (client VirtualNetworkGatewayConnectionsClient) ResetSharedKeyPreparer(reso // ResetSharedKeySender sends the ResetSharedKey request. The method will close the // http.Response Body if it receives an error. func (client VirtualNetworkGatewayConnectionsClient) ResetSharedKeySender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // ResetSharedKeyResponder handles the response to the ResetSharedKey request. The method always // closes the http.Response Body. -func (client VirtualNetworkGatewayConnectionsClient) ResetSharedKeyResponder(resp *http.Response) (result ConnectionResetSharedKey, err error) { +func (client VirtualNetworkGatewayConnectionsClient) ResetSharedKeyResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + result.Response = resp return } // SetSharedKey the Put VirtualNetworkGatewayConnectionSharedKey operation // sets the virtual network gateway connection shared key for passed virtual // network gateway connection in the specified resource group through Network -// resource provider. +// resource provider. This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. // virtualNetworkGatewayConnectionName is the virtual network gateway // connection name. parameters is parameters supplied to the Begin Set // Virtual Network Gateway conection Shared key operation throughNetwork // resource provider. -func (client VirtualNetworkGatewayConnectionsClient) SetSharedKey(resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters ConnectionSharedKey) (result ConnectionSharedKey, ae error) { - req, err := client.SetSharedKeyPreparer(resourceGroupName, virtualNetworkGatewayConnectionName, parameters) +func (client VirtualNetworkGatewayConnectionsClient) SetSharedKey(resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters ConnectionSharedKey, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.SetSharedKeyPreparer(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/VirtualNetworkGatewayConnectionsClient", "SetSharedKey", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "SetSharedKey", nil, "Failure preparing request") } resp, err := client.SetSharedKeySender(req) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/VirtualNetworkGatewayConnectionsClient", "SetSharedKey", resp.StatusCode, "Failure sending request") + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "SetSharedKey", resp, "Failure sending request") } result, err = client.SetSharedKeyResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/VirtualNetworkGatewayConnectionsClient", "SetSharedKey", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "SetSharedKey", resp, "Failure responding to request") } return } // SetSharedKeyPreparer prepares the SetSharedKey request. -func (client VirtualNetworkGatewayConnectionsClient) SetSharedKeyPreparer(resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters ConnectionSharedKey) (*http.Request, error) { +func (client VirtualNetworkGatewayConnectionsClient) SetSharedKeyPreparer(resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters ConnectionSharedKey, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "subscriptionId": url.QueryEscape(client.SubscriptionID), @@ -515,7 +529,7 @@ func (client VirtualNetworkGatewayConnectionsClient) SetSharedKeyPreparer(resour "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), @@ -528,18 +542,19 @@ func (client VirtualNetworkGatewayConnectionsClient) SetSharedKeyPreparer(resour // SetSharedKeySender sends the SetSharedKey request. The method will close the // http.Response Body if it receives an error. func (client VirtualNetworkGatewayConnectionsClient) SetSharedKeySender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusCreated, http.StatusOK) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // SetSharedKeyResponder handles the response to the SetSharedKey request. The method always // closes the http.Response Body. -func (client VirtualNetworkGatewayConnectionsClient) SetSharedKeyResponder(resp *http.Response) (result ConnectionSharedKey, err error) { +func (client VirtualNetworkGatewayConnectionsClient) SetSharedKeyResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), - autorest.ByUnmarshallingJSON(&result), + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + result.Response = resp return } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/virtualnetworkgateways.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/virtualnetworkgateways.go index d5e69686a884..2649c4eb230a 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/virtualnetworkgateways.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/virtualnetworkgateways.go @@ -14,12 +14,13 @@ package network // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -47,34 +48,36 @@ func NewVirtualNetworkGatewaysClientWithBaseURI(baseURI string, subscriptionID s // CreateOrUpdate the Put VirtualNetworkGateway operation creates/updates a // virtual network gateway in the specified resource group through Network -// resource provider. +// resource provider. This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. // virtualNetworkGatewayName is the name of the virtual network gateway. // parameters is parameters supplied to the Begin Create or update Virtual // Network Gateway operation through Network resource provider. -func (client VirtualNetworkGatewaysClient) CreateOrUpdate(resourceGroupName string, virtualNetworkGatewayName string, parameters VirtualNetworkGateway) (result VirtualNetworkGateway, ae error) { - req, err := client.CreateOrUpdatePreparer(resourceGroupName, virtualNetworkGatewayName, parameters) +func (client VirtualNetworkGatewaysClient) CreateOrUpdate(resourceGroupName string, virtualNetworkGatewayName string, parameters VirtualNetworkGateway, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, virtualNetworkGatewayName, parameters, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/VirtualNetworkGatewaysClient", "CreateOrUpdate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "CreateOrUpdate", nil, "Failure preparing request") } resp, err := client.CreateOrUpdateSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/VirtualNetworkGatewaysClient", "CreateOrUpdate", resp.StatusCode, "Failure sending request") + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "CreateOrUpdate", resp, "Failure sending request") } result, err = client.CreateOrUpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/VirtualNetworkGatewaysClient", "CreateOrUpdate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "CreateOrUpdate", resp, "Failure responding to request") } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualNetworkGatewaysClient) CreateOrUpdatePreparer(resourceGroupName string, virtualNetworkGatewayName string, parameters VirtualNetworkGateway) (*http.Request, error) { +func (client VirtualNetworkGatewaysClient) CreateOrUpdatePreparer(resourceGroupName string, virtualNetworkGatewayName string, parameters VirtualNetworkGateway, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "subscriptionId": url.QueryEscape(client.SubscriptionID), @@ -85,7 +88,7 @@ func (client VirtualNetworkGatewaysClient) CreateOrUpdatePreparer(resourceGroupN "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), @@ -98,49 +101,53 @@ func (client VirtualNetworkGatewaysClient) CreateOrUpdatePreparer(resourceGroupN // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client VirtualNetworkGatewaysClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusCreated) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualNetworkGateway, err error) { +func (client VirtualNetworkGatewaysClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + result.Response = resp return } // Delete the Delete VirtualNetworkGateway operation deletes the specifed -// virtual network Gateway through Network resource provider. +// virtual network Gateway through Network resource provider. This method may +// poll for completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. // // resourceGroupName is the name of the resource group. // virtualNetworkGatewayName is the name of the virtual network gateway. -func (client VirtualNetworkGatewaysClient) Delete(resourceGroupName string, virtualNetworkGatewayName string) (result autorest.Response, ae error) { - req, err := client.DeletePreparer(resourceGroupName, virtualNetworkGatewayName) +func (client VirtualNetworkGatewaysClient) Delete(resourceGroupName string, virtualNetworkGatewayName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, virtualNetworkGatewayName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/VirtualNetworkGatewaysClient", "Delete", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Delete", nil, "Failure preparing request") } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "network/VirtualNetworkGatewaysClient", "Delete", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Delete", resp, "Failure sending request") } result, err = client.DeleteResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/VirtualNetworkGatewaysClient", "Delete", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Delete", resp, "Failure responding to request") } return } // DeletePreparer prepares the Delete request. -func (client VirtualNetworkGatewaysClient) DeletePreparer(resourceGroupName string, virtualNetworkGatewayName string) (*http.Request, error) { +func (client VirtualNetworkGatewaysClient) DeletePreparer(resourceGroupName string, virtualNetworkGatewayName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "subscriptionId": url.QueryEscape(client.SubscriptionID), @@ -151,11 +158,11 @@ func (client VirtualNetworkGatewaysClient) DeletePreparer(resourceGroupName stri "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), - autorest.WithPath("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/"), + autorest.WithPath("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualnetworkgateways/{virtualNetworkGatewayName}"), autorest.WithPathParameters(pathParameters), autorest.WithQueryParameters(queryParameters)) } @@ -163,7 +170,9 @@ func (client VirtualNetworkGatewaysClient) DeletePreparer(resourceGroupName stri // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client VirtualNetworkGatewaysClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusNoContent, http.StatusAccepted, http.StatusOK) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // DeleteResponder handles the response to the Delete request. The method always @@ -172,7 +181,7 @@ func (client VirtualNetworkGatewaysClient) DeleteResponder(resp *http.Response) err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusAccepted, http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusAccepted, http.StatusOK), autorest.ByClosing()) result.Response = resp return @@ -186,21 +195,21 @@ func (client VirtualNetworkGatewaysClient) DeleteResponder(resp *http.Response) // virtualNetworkGatewayName is the name of the virtual network gateway. // parameters is parameters supplied to the Begin Generating Virtual Network // Gateway Vpn client package operation through Network resource provider. -func (client VirtualNetworkGatewaysClient) Generatevpnclientpackage(resourceGroupName string, virtualNetworkGatewayName string, parameters VpnClientParameters) (result String, ae error) { +func (client VirtualNetworkGatewaysClient) Generatevpnclientpackage(resourceGroupName string, virtualNetworkGatewayName string, parameters VpnClientParameters) (result String, err error) { req, err := client.GeneratevpnclientpackagePreparer(resourceGroupName, virtualNetworkGatewayName, parameters) if err != nil { - return result, autorest.NewErrorWithError(err, "network/VirtualNetworkGatewaysClient", "Generatevpnclientpackage", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Generatevpnclientpackage", nil, "Failure preparing request") } resp, err := client.GeneratevpnclientpackageSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/VirtualNetworkGatewaysClient", "Generatevpnclientpackage", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Generatevpnclientpackage", resp, "Failure sending request") } result, err = client.GeneratevpnclientpackageResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/VirtualNetworkGatewaysClient", "Generatevpnclientpackage", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Generatevpnclientpackage", resp, "Failure responding to request") } return @@ -231,7 +240,7 @@ func (client VirtualNetworkGatewaysClient) GeneratevpnclientpackagePreparer(reso // GeneratevpnclientpackageSender sends the Generatevpnclientpackage request. The method will close the // http.Response Body if it receives an error. func (client VirtualNetworkGatewaysClient) GeneratevpnclientpackageSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted) + return autorest.SendWithSender(client, req) } // GeneratevpnclientpackageResponder handles the response to the Generatevpnclientpackage request. The method always @@ -240,7 +249,7 @@ func (client VirtualNetworkGatewaysClient) GeneratevpnclientpackageResponder(res err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByUnmarshallingJSON(&result.Value), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -252,21 +261,21 @@ func (client VirtualNetworkGatewaysClient) GeneratevpnclientpackageResponder(res // // resourceGroupName is the name of the resource group. // virtualNetworkGatewayName is the name of the virtual network gateway. -func (client VirtualNetworkGatewaysClient) Get(resourceGroupName string, virtualNetworkGatewayName string) (result VirtualNetworkGateway, ae error) { +func (client VirtualNetworkGatewaysClient) Get(resourceGroupName string, virtualNetworkGatewayName string) (result VirtualNetworkGateway, err error) { req, err := client.GetPreparer(resourceGroupName, virtualNetworkGatewayName) if err != nil { - return result, autorest.NewErrorWithError(err, "network/VirtualNetworkGatewaysClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/VirtualNetworkGatewaysClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/VirtualNetworkGatewaysClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Get", resp, "Failure responding to request") } return @@ -296,7 +305,7 @@ func (client VirtualNetworkGatewaysClient) GetPreparer(resourceGroupName string, // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client VirtualNetworkGatewaysClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -305,7 +314,7 @@ func (client VirtualNetworkGatewaysClient) GetResponder(resp *http.Response) (re err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -316,21 +325,21 @@ func (client VirtualNetworkGatewaysClient) GetResponder(resp *http.Response) (re // network gateways stored. // // resourceGroupName is the name of the resource group. -func (client VirtualNetworkGatewaysClient) List(resourceGroupName string) (result VirtualNetworkGatewayListResult, ae error) { +func (client VirtualNetworkGatewaysClient) List(resourceGroupName string) (result VirtualNetworkGatewayListResult, err error) { req, err := client.ListPreparer(resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "network/VirtualNetworkGatewaysClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/VirtualNetworkGatewaysClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/VirtualNetworkGatewaysClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "List", resp, "Failure responding to request") } return @@ -359,7 +368,7 @@ func (client VirtualNetworkGatewaysClient) ListPreparer(resourceGroupName string // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client VirtualNetworkGatewaysClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -368,7 +377,7 @@ func (client VirtualNetworkGatewaysClient) ListResponder(resp *http.Response) (r err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -376,10 +385,10 @@ func (client VirtualNetworkGatewaysClient) ListResponder(resp *http.Response) (r } // ListNextResults retrieves the next set of results, if any. -func (client VirtualNetworkGatewaysClient) ListNextResults(lastResults VirtualNetworkGatewayListResult) (result VirtualNetworkGatewayListResult, ae error) { +func (client VirtualNetworkGatewaysClient) ListNextResults(lastResults VirtualNetworkGatewayListResult) (result VirtualNetworkGatewayListResult, err error) { req, err := lastResults.VirtualNetworkGatewayListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/VirtualNetworkGatewaysClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -388,12 +397,12 @@ func (client VirtualNetworkGatewaysClient) ListNextResults(lastResults VirtualNe resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/VirtualNetworkGatewaysClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/VirtualNetworkGatewaysClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "List", resp, "Failure responding to next results request request") } return @@ -401,34 +410,36 @@ func (client VirtualNetworkGatewaysClient) ListNextResults(lastResults VirtualNe // Reset the Reset VirtualNetworkGateway operation resets the primary of the // virtual network gateway in the specified resource group through Network -// resource provider. +// resource provider. This method may poll for completion. Polling can be +// canceled by passing the cancel channel argument. The channel will be used +// to cancel polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. // virtualNetworkGatewayName is the name of the virtual network gateway. // parameters is parameters supplied to the Begin Reset Virtual Network // Gateway operation through Network resource provider. -func (client VirtualNetworkGatewaysClient) Reset(resourceGroupName string, virtualNetworkGatewayName string, parameters VirtualNetworkGateway) (result VirtualNetworkGateway, ae error) { - req, err := client.ResetPreparer(resourceGroupName, virtualNetworkGatewayName, parameters) +func (client VirtualNetworkGatewaysClient) Reset(resourceGroupName string, virtualNetworkGatewayName string, parameters VirtualNetworkGateway, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.ResetPreparer(resourceGroupName, virtualNetworkGatewayName, parameters, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/VirtualNetworkGatewaysClient", "Reset", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Reset", nil, "Failure preparing request") } resp, err := client.ResetSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/VirtualNetworkGatewaysClient", "Reset", resp.StatusCode, "Failure sending request") + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Reset", resp, "Failure sending request") } result, err = client.ResetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/VirtualNetworkGatewaysClient", "Reset", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Reset", resp, "Failure responding to request") } return } // ResetPreparer prepares the Reset request. -func (client VirtualNetworkGatewaysClient) ResetPreparer(resourceGroupName string, virtualNetworkGatewayName string, parameters VirtualNetworkGateway) (*http.Request, error) { +func (client VirtualNetworkGatewaysClient) ResetPreparer(resourceGroupName string, virtualNetworkGatewayName string, parameters VirtualNetworkGateway, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "subscriptionId": url.QueryEscape(client.SubscriptionID), @@ -439,7 +450,7 @@ func (client VirtualNetworkGatewaysClient) ResetPreparer(resourceGroupName strin "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), @@ -452,18 +463,19 @@ func (client VirtualNetworkGatewaysClient) ResetPreparer(resourceGroupName strin // ResetSender sends the Reset request. The method will close the // http.Response Body if it receives an error. func (client VirtualNetworkGatewaysClient) ResetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusAccepted, http.StatusOK) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // ResetResponder handles the response to the Reset request. The method always // closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) ResetResponder(resp *http.Response) (result VirtualNetworkGateway, err error) { +func (client VirtualNetworkGatewaysClient) ResetResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusOK), - autorest.ByUnmarshallingJSON(&result), + azure.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusOK), autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + result.Response = resp return } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/virtualnetworks.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/virtualnetworks.go index 148681a5ca41..bb50a7f01e8b 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/virtualnetworks.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/virtualnetworks.go @@ -14,12 +14,13 @@ package network // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -46,33 +47,36 @@ func NewVirtualNetworksClientWithBaseURI(baseURI string, subscriptionID string) } // CreateOrUpdate the Put VirtualNetwork operation creates/updates a virtual -// network in the specified resource group. +// network in the specified resource group. This method may poll for +// completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. // // resourceGroupName is the name of the resource group. virtualNetworkName is // the name of the virtual network. parameters is parameters supplied to the // create/update Virtual Network operation -func (client VirtualNetworksClient) CreateOrUpdate(resourceGroupName string, virtualNetworkName string, parameters VirtualNetwork) (result VirtualNetwork, ae error) { - req, err := client.CreateOrUpdatePreparer(resourceGroupName, virtualNetworkName, parameters) +func (client VirtualNetworksClient) CreateOrUpdate(resourceGroupName string, virtualNetworkName string, parameters VirtualNetwork, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, virtualNetworkName, parameters, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/VirtualNetworksClient", "CreateOrUpdate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "CreateOrUpdate", nil, "Failure preparing request") } resp, err := client.CreateOrUpdateSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/VirtualNetworksClient", "CreateOrUpdate", resp.StatusCode, "Failure sending request") + result.Response = resp + return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "CreateOrUpdate", resp, "Failure sending request") } result, err = client.CreateOrUpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/VirtualNetworksClient", "CreateOrUpdate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "CreateOrUpdate", resp, "Failure responding to request") } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualNetworksClient) CreateOrUpdatePreparer(resourceGroupName string, virtualNetworkName string, parameters VirtualNetwork) (*http.Request, error) { +func (client VirtualNetworksClient) CreateOrUpdatePreparer(resourceGroupName string, virtualNetworkName string, parameters VirtualNetwork, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "subscriptionId": url.QueryEscape(client.SubscriptionID), @@ -83,7 +87,7 @@ func (client VirtualNetworksClient) CreateOrUpdatePreparer(resourceGroupName str "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), @@ -96,49 +100,52 @@ func (client VirtualNetworksClient) CreateOrUpdatePreparer(resourceGroupName str // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client VirtualNetworksClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusCreated) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client VirtualNetworksClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualNetwork, err error) { +func (client VirtualNetworksClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + result.Response = resp return } // Delete the Delete VirtualNetwork operation deletes the specifed virtual -// network +// network This method may poll for completion. Polling can be canceled by +// passing the cancel channel argument. The channel will be used to cancel +// polling and any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. virtualNetworkName is // the name of the virtual network. -func (client VirtualNetworksClient) Delete(resourceGroupName string, virtualNetworkName string) (result autorest.Response, ae error) { - req, err := client.DeletePreparer(resourceGroupName, virtualNetworkName) +func (client VirtualNetworksClient) Delete(resourceGroupName string, virtualNetworkName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, virtualNetworkName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "network/VirtualNetworksClient", "Delete", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "Delete", nil, "Failure preparing request") } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "network/VirtualNetworksClient", "Delete", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "Delete", resp, "Failure sending request") } result, err = client.DeleteResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/VirtualNetworksClient", "Delete", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "Delete", resp, "Failure responding to request") } return } // DeletePreparer prepares the Delete request. -func (client VirtualNetworksClient) DeletePreparer(resourceGroupName string, virtualNetworkName string) (*http.Request, error) { +func (client VirtualNetworksClient) DeletePreparer(resourceGroupName string, virtualNetworkName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "subscriptionId": url.QueryEscape(client.SubscriptionID), @@ -149,7 +156,7 @@ func (client VirtualNetworksClient) DeletePreparer(resourceGroupName string, vir "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), @@ -161,7 +168,9 @@ func (client VirtualNetworksClient) DeletePreparer(resourceGroupName string, vir // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client VirtualNetworksClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusAccepted, http.StatusNoContent, http.StatusOK) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // DeleteResponder handles the response to the Delete request. The method always @@ -170,7 +179,7 @@ func (client VirtualNetworksClient) DeleteResponder(resp *http.Response) (result err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusNoContent, http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusNoContent, http.StatusOK), autorest.ByClosing()) result.Response = resp return @@ -181,21 +190,21 @@ func (client VirtualNetworksClient) DeleteResponder(resp *http.Response) (result // // resourceGroupName is the name of the resource group. virtualNetworkName is // the name of the virtual network. expand is expand references resources. -func (client VirtualNetworksClient) Get(resourceGroupName string, virtualNetworkName string, expand string) (result VirtualNetwork, ae error) { +func (client VirtualNetworksClient) Get(resourceGroupName string, virtualNetworkName string, expand string) (result VirtualNetwork, err error) { req, err := client.GetPreparer(resourceGroupName, virtualNetworkName, expand) if err != nil { - return result, autorest.NewErrorWithError(err, "network/VirtualNetworksClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/VirtualNetworksClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/VirtualNetworksClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "Get", resp, "Failure responding to request") } return @@ -228,7 +237,7 @@ func (client VirtualNetworksClient) GetPreparer(resourceGroupName string, virtua // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client VirtualNetworksClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -237,7 +246,7 @@ func (client VirtualNetworksClient) GetResponder(resp *http.Response) (result Vi err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -248,21 +257,21 @@ func (client VirtualNetworksClient) GetResponder(resp *http.Response) (result Vi // group // // resourceGroupName is the name of the resource group. -func (client VirtualNetworksClient) List(resourceGroupName string) (result VirtualNetworkListResult, ae error) { +func (client VirtualNetworksClient) List(resourceGroupName string) (result VirtualNetworkListResult, err error) { req, err := client.ListPreparer(resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "network/VirtualNetworksClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/VirtualNetworksClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/VirtualNetworksClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "List", resp, "Failure responding to request") } return @@ -291,7 +300,7 @@ func (client VirtualNetworksClient) ListPreparer(resourceGroupName string) (*htt // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client VirtualNetworksClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -300,7 +309,7 @@ func (client VirtualNetworksClient) ListResponder(resp *http.Response) (result V err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -308,10 +317,10 @@ func (client VirtualNetworksClient) ListResponder(resp *http.Response) (result V } // ListNextResults retrieves the next set of results, if any. -func (client VirtualNetworksClient) ListNextResults(lastResults VirtualNetworkListResult) (result VirtualNetworkListResult, ae error) { +func (client VirtualNetworksClient) ListNextResults(lastResults VirtualNetworkListResult) (result VirtualNetworkListResult, err error) { req, err := lastResults.VirtualNetworkListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/VirtualNetworksClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -320,12 +329,12 @@ func (client VirtualNetworksClient) ListNextResults(lastResults VirtualNetworkLi resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/VirtualNetworksClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/VirtualNetworksClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "List", resp, "Failure responding to next results request request") } return @@ -333,21 +342,21 @@ func (client VirtualNetworksClient) ListNextResults(lastResults VirtualNetworkLi // ListAll the list VirtualNetwork returns all Virtual Networks in a // subscription -func (client VirtualNetworksClient) ListAll() (result VirtualNetworkListResult, ae error) { +func (client VirtualNetworksClient) ListAll() (result VirtualNetworkListResult, err error) { req, err := client.ListAllPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/VirtualNetworksClient", "ListAll", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "ListAll", nil, "Failure preparing request") } resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/VirtualNetworksClient", "ListAll", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "ListAll", resp, "Failure sending request") } result, err = client.ListAllResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/VirtualNetworksClient", "ListAll", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "ListAll", resp, "Failure responding to request") } return @@ -375,7 +384,7 @@ func (client VirtualNetworksClient) ListAllPreparer() (*http.Request, error) { // ListAllSender sends the ListAll request. The method will close the // http.Response Body if it receives an error. func (client VirtualNetworksClient) ListAllSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListAllResponder handles the response to the ListAll request. The method always @@ -384,7 +393,7 @@ func (client VirtualNetworksClient) ListAllResponder(resp *http.Response) (resul err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -392,10 +401,10 @@ func (client VirtualNetworksClient) ListAllResponder(resp *http.Response) (resul } // ListAllNextResults retrieves the next set of results, if any. -func (client VirtualNetworksClient) ListAllNextResults(lastResults VirtualNetworkListResult) (result VirtualNetworkListResult, ae error) { +func (client VirtualNetworksClient) ListAllNextResults(lastResults VirtualNetworkListResult) (result VirtualNetworkListResult, err error) { req, err := lastResults.VirtualNetworkListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network/VirtualNetworksClient", "ListAll", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "ListAll", nil, "Failure preparing next results request request") } if req == nil { return @@ -404,12 +413,12 @@ func (client VirtualNetworksClient) ListAllNextResults(lastResults VirtualNetwor resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network/VirtualNetworksClient", "ListAll", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "ListAll", resp, "Failure sending next results request request") } result, err = client.ListAllResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "network/VirtualNetworksClient", "ListAll", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "ListAll", resp, "Failure responding to next results request request") } return diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/client.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/client.go index 81bd73568f75..687c905ef060 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/client.go @@ -1,3 +1,6 @@ +// Package resources implements the Azure ARM Resources service API version +// 2015-11-01. +// package resources // Copyright (c) Microsoft and contributors. All rights reserved. @@ -14,19 +17,20 @@ package resources // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) const ( // APIVersion is the version of the Resources - APIVersion = "2014-04-01-preview" + APIVersion = "2015-11-01" // DefaultBaseURI is the default URI used for the service Resources DefaultBaseURI = "https://management.azure.com" @@ -59,21 +63,21 @@ func NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient { // insensitive. resourceProviderNamespace is resource identity. // parentResourcePath is resource identity. resourceType is resource // identity. resourceName is resource identity. -func (client ManagementClient) CheckExistence(resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, apiVersion string) (result autorest.Response, ae error) { +func (client ManagementClient) CheckExistence(resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, apiVersion string) (result autorest.Response, err error) { req, err := client.CheckExistencePreparer(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/ManagementClient", "CheckExistence", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.ManagementClient", "CheckExistence", nil, "Failure preparing request") } resp, err := client.CheckExistenceSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "resources/ManagementClient", "CheckExistence", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.ManagementClient", "CheckExistence", resp, "Failure sending request") } result, err = client.CheckExistenceResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/ManagementClient", "CheckExistence", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.ManagementClient", "CheckExistence", resp, "Failure responding to request") } return @@ -106,7 +110,7 @@ func (client ManagementClient) CheckExistencePreparer(resourceGroupName string, // CheckExistenceSender sends the CheckExistence request. The method will close the // http.Response Body if it receives an error. func (client ManagementClient) CheckExistenceSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusNoContent, http.StatusNotFound) + return autorest.SendWithSender(client, req) } // CheckExistenceResponder handles the response to the CheckExistence request. The method always @@ -115,7 +119,7 @@ func (client ManagementClient) CheckExistenceResponder(resp *http.Response) (res err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent, http.StatusNotFound), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent, http.StatusNotFound), autorest.ByClosing()) result.Response = resp return @@ -128,21 +132,21 @@ func (client ManagementClient) CheckExistenceResponder(resp *http.Response) (res // parentResourcePath is resource identity. resourceType is resource // identity. resourceName is resource identity. parameters is create or // update resource parameters. -func (client ManagementClient) CreateOrUpdate(resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, apiVersion string, parameters GenericResource) (result GenericResource, ae error) { +func (client ManagementClient) CreateOrUpdate(resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, apiVersion string, parameters GenericResource) (result GenericResource, err error) { req, err := client.CreateOrUpdatePreparer(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion, parameters) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/ManagementClient", "CreateOrUpdate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.ManagementClient", "CreateOrUpdate", nil, "Failure preparing request") } resp, err := client.CreateOrUpdateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/ManagementClient", "CreateOrUpdate", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.ManagementClient", "CreateOrUpdate", resp, "Failure sending request") } result, err = client.CreateOrUpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/ManagementClient", "CreateOrUpdate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.ManagementClient", "CreateOrUpdate", resp, "Failure responding to request") } return @@ -176,7 +180,7 @@ func (client ManagementClient) CreateOrUpdatePreparer(resourceGroupName string, // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client ManagementClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusCreated, http.StatusOK) + return autorest.SendWithSender(client, req) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always @@ -185,7 +189,7 @@ func (client ManagementClient) CreateOrUpdateResponder(resp *http.Response) (res err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -198,21 +202,21 @@ func (client ManagementClient) CreateOrUpdateResponder(resp *http.Response) (res // insensitive. resourceProviderNamespace is resource identity. // parentResourcePath is resource identity. resourceType is resource // identity. resourceName is resource identity. -func (client ManagementClient) Delete(resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, apiVersion string) (result autorest.Response, ae error) { +func (client ManagementClient) Delete(resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, apiVersion string) (result autorest.Response, err error) { req, err := client.DeletePreparer(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/ManagementClient", "Delete", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.ManagementClient", "Delete", nil, "Failure preparing request") } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "resources/ManagementClient", "Delete", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.ManagementClient", "Delete", resp, "Failure sending request") } result, err = client.DeleteResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/ManagementClient", "Delete", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.ManagementClient", "Delete", resp, "Failure responding to request") } return @@ -245,7 +249,7 @@ func (client ManagementClient) DeletePreparer(resourceGroupName string, resource // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client ManagementClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusNoContent, http.StatusAccepted) + return autorest.SendWithSender(client, req) } // DeleteResponder handles the response to the Delete request. The method always @@ -254,7 +258,7 @@ func (client ManagementClient) DeleteResponder(resp *http.Response) (result auto err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent, http.StatusAccepted), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return @@ -266,21 +270,21 @@ func (client ManagementClient) DeleteResponder(resp *http.Response) (result auto // insensitive. resourceProviderNamespace is resource identity. // parentResourcePath is resource identity. resourceType is resource // identity. resourceName is resource identity. -func (client ManagementClient) Get(resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, apiVersion string) (result GenericResource, ae error) { +func (client ManagementClient) Get(resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, apiVersion string) (result GenericResource, err error) { req, err := client.GetPreparer(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/ManagementClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.ManagementClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/ManagementClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.ManagementClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/ManagementClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.ManagementClient", "Get", resp, "Failure responding to request") } return @@ -313,7 +317,7 @@ func (client ManagementClient) GetPreparer(resourceGroupName string, resourcePro // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client ManagementClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusNoContent) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -322,7 +326,7 @@ func (client ManagementClient) GetResponder(resp *http.Response) (result Generic err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -333,28 +337,28 @@ func (client ManagementClient) GetResponder(resp *http.Response) (result Generic // // filter is the filter to apply on the operation. top is query parameters. If // null is passed returns all resource groups. -func (client ManagementClient) List(filter string, top *int) (result ResourceListResult, ae error) { +func (client ManagementClient) List(filter string, top *int32) (result ResourceListResult, err error) { req, err := client.ListPreparer(filter, top) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/ManagementClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.ManagementClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/ManagementClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.ManagementClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/ManagementClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.ManagementClient", "List", resp, "Failure responding to request") } return } // ListPreparer prepares the List request. -func (client ManagementClient) ListPreparer(filter string, top *int) (*http.Request, error) { +func (client ManagementClient) ListPreparer(filter string, top *int32) (*http.Request, error) { pathParameters := map[string]interface{}{ "subscriptionId": url.QueryEscape(client.SubscriptionID), } @@ -381,7 +385,7 @@ func (client ManagementClient) ListPreparer(filter string, top *int) (*http.Requ // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client ManagementClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -390,7 +394,7 @@ func (client ManagementClient) ListResponder(resp *http.Response) (result Resour err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -398,10 +402,10 @@ func (client ManagementClient) ListResponder(resp *http.Response) (result Resour } // ListNextResults retrieves the next set of results, if any. -func (client ManagementClient) ListNextResults(lastResults ResourceListResult) (result ResourceListResult, ae error) { +func (client ManagementClient) ListNextResults(lastResults ResourceListResult) (result ResourceListResult, err error) { req, err := lastResults.ResourceListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "resources/ManagementClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "resources.ManagementClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -410,44 +414,47 @@ func (client ManagementClient) ListNextResults(lastResults ResourceListResult) ( resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/ManagementClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "resources.ManagementClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/ManagementClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "resources.ManagementClient", "List", resp, "Failure responding to next results request request") } return } // MoveResources begin moving resources.To determine whether the operation has -// finished processing the request, call GetLongRunningOperationStatus. +// finished processing the request, call GetLongRunningOperationStatus. This +// method may poll for completion. Polling can be canceled by passing the +// cancel channel argument. The channel will be used to cancel polling and +// any outstanding HTTP requests. // // sourceResourceGroupName is source resource group name. parameters is move // resources' parameters. -func (client ManagementClient) MoveResources(sourceResourceGroupName string, parameters MoveInfo) (result autorest.Response, ae error) { - req, err := client.MoveResourcesPreparer(sourceResourceGroupName, parameters) +func (client ManagementClient) MoveResources(sourceResourceGroupName string, parameters MoveInfo, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.MoveResourcesPreparer(sourceResourceGroupName, parameters, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/ManagementClient", "MoveResources", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.ManagementClient", "MoveResources", nil, "Failure preparing request") } resp, err := client.MoveResourcesSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "resources/ManagementClient", "MoveResources", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.ManagementClient", "MoveResources", resp, "Failure sending request") } result, err = client.MoveResourcesResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/ManagementClient", "MoveResources", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.ManagementClient", "MoveResources", resp, "Failure responding to request") } return } // MoveResourcesPreparer prepares the MoveResources request. -func (client ManagementClient) MoveResourcesPreparer(sourceResourceGroupName string, parameters MoveInfo) (*http.Request, error) { +func (client ManagementClient) MoveResourcesPreparer(sourceResourceGroupName string, parameters MoveInfo, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "sourceResourceGroupName": url.QueryEscape(sourceResourceGroupName), "subscriptionId": url.QueryEscape(client.SubscriptionID), @@ -457,7 +464,7 @@ func (client ManagementClient) MoveResourcesPreparer(sourceResourceGroupName str "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), @@ -470,7 +477,9 @@ func (client ManagementClient) MoveResourcesPreparer(sourceResourceGroupName str // MoveResourcesSender sends the MoveResources request. The method will close the // http.Response Body if it receives an error. func (client ManagementClient) MoveResourcesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted, http.StatusNoContent) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // MoveResourcesResponder handles the response to the MoveResources request. The method always @@ -479,7 +488,7 @@ func (client ManagementClient) MoveResourcesResponder(resp *http.Response) (resu err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/deploymentoperations.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/deploymentoperations.go index 3c042f089159..abdcf3f20d6a 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/deploymentoperations.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/deploymentoperations.go @@ -14,12 +14,13 @@ package resources // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -47,21 +48,21 @@ func NewDeploymentOperationsClientWithBaseURI(baseURI string, subscriptionID str // resourceGroupName is the name of the resource group. The name is case // insensitive. deploymentName is the name of the deployment. operationID is // operation Id. -func (client DeploymentOperationsClient) Get(resourceGroupName string, deploymentName string, operationID string) (result DeploymentOperation, ae error) { +func (client DeploymentOperationsClient) Get(resourceGroupName string, deploymentName string, operationID string) (result DeploymentOperation, err error) { req, err := client.GetPreparer(resourceGroupName, deploymentName, operationID) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/DeploymentOperationsClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.DeploymentOperationsClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/DeploymentOperationsClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.DeploymentOperationsClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/DeploymentOperationsClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.DeploymentOperationsClient", "Get", resp, "Failure responding to request") } return @@ -92,7 +93,7 @@ func (client DeploymentOperationsClient) GetPreparer(resourceGroupName string, d // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client DeploymentOperationsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -101,7 +102,7 @@ func (client DeploymentOperationsClient) GetResponder(resp *http.Response) (resu err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -113,28 +114,28 @@ func (client DeploymentOperationsClient) GetResponder(resp *http.Response) (resu // resourceGroupName is the name of the resource group. The name is case // insensitive. deploymentName is the name of the deployment. top is query // parameters. -func (client DeploymentOperationsClient) List(resourceGroupName string, deploymentName string, top *int) (result DeploymentOperationsListResult, ae error) { +func (client DeploymentOperationsClient) List(resourceGroupName string, deploymentName string, top *int32) (result DeploymentOperationsListResult, err error) { req, err := client.ListPreparer(resourceGroupName, deploymentName, top) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/DeploymentOperationsClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.DeploymentOperationsClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/DeploymentOperationsClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.DeploymentOperationsClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/DeploymentOperationsClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.DeploymentOperationsClient", "List", resp, "Failure responding to request") } return } // ListPreparer prepares the List request. -func (client DeploymentOperationsClient) ListPreparer(resourceGroupName string, deploymentName string, top *int) (*http.Request, error) { +func (client DeploymentOperationsClient) ListPreparer(resourceGroupName string, deploymentName string, top *int32) (*http.Request, error) { pathParameters := map[string]interface{}{ "deploymentName": url.QueryEscape(deploymentName), "resourceGroupName": url.QueryEscape(resourceGroupName), @@ -160,7 +161,7 @@ func (client DeploymentOperationsClient) ListPreparer(resourceGroupName string, // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client DeploymentOperationsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -169,7 +170,7 @@ func (client DeploymentOperationsClient) ListResponder(resp *http.Response) (res err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -177,10 +178,10 @@ func (client DeploymentOperationsClient) ListResponder(resp *http.Response) (res } // ListNextResults retrieves the next set of results, if any. -func (client DeploymentOperationsClient) ListNextResults(lastResults DeploymentOperationsListResult) (result DeploymentOperationsListResult, ae error) { +func (client DeploymentOperationsClient) ListNextResults(lastResults DeploymentOperationsListResult) (result DeploymentOperationsListResult, err error) { req, err := lastResults.DeploymentOperationsListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "resources/DeploymentOperationsClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "resources.DeploymentOperationsClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -189,12 +190,12 @@ func (client DeploymentOperationsClient) ListNextResults(lastResults DeploymentO resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/DeploymentOperationsClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "resources.DeploymentOperationsClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/DeploymentOperationsClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "resources.DeploymentOperationsClient", "List", resp, "Failure responding to next results request request") } return diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/deployments.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/deployments.go index b7f940726d22..4f61041d2221 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/deployments.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/deployments.go @@ -14,12 +14,13 @@ package resources // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -45,21 +46,21 @@ func NewDeploymentsClientWithBaseURI(baseURI string, subscriptionID string) Depl // // resourceGroupName is the name of the resource group. The name is case // insensitive. deploymentName is the name of the deployment. -func (client DeploymentsClient) Cancel(resourceGroupName string, deploymentName string) (result autorest.Response, ae error) { +func (client DeploymentsClient) Cancel(resourceGroupName string, deploymentName string) (result autorest.Response, err error) { req, err := client.CancelPreparer(resourceGroupName, deploymentName) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/DeploymentsClient", "Cancel", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.DeploymentsClient", "Cancel", nil, "Failure preparing request") } resp, err := client.CancelSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "resources/DeploymentsClient", "Cancel", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.DeploymentsClient", "Cancel", resp, "Failure sending request") } result, err = client.CancelResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/DeploymentsClient", "Cancel", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.DeploymentsClient", "Cancel", resp, "Failure responding to request") } return @@ -89,7 +90,7 @@ func (client DeploymentsClient) CancelPreparer(resourceGroupName string, deploym // CancelSender sends the Cancel request. The method will close the // http.Response Body if it receives an error. func (client DeploymentsClient) CancelSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusNoContent) + return autorest.SendWithSender(client, req) } // CancelResponder handles the response to the Cancel request. The method always @@ -98,7 +99,7 @@ func (client DeploymentsClient) CancelResponder(resp *http.Response) (result aut err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return @@ -108,21 +109,21 @@ func (client DeploymentsClient) CancelResponder(resp *http.Response) (result aut // // resourceGroupName is the name of the resource group to check. The name is // case insensitive. deploymentName is the name of the deployment. -func (client DeploymentsClient) CheckExistence(resourceGroupName string, deploymentName string) (result autorest.Response, ae error) { +func (client DeploymentsClient) CheckExistence(resourceGroupName string, deploymentName string) (result autorest.Response, err error) { req, err := client.CheckExistencePreparer(resourceGroupName, deploymentName) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/DeploymentsClient", "CheckExistence", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.DeploymentsClient", "CheckExistence", nil, "Failure preparing request") } resp, err := client.CheckExistenceSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "resources/DeploymentsClient", "CheckExistence", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.DeploymentsClient", "CheckExistence", resp, "Failure sending request") } result, err = client.CheckExistenceResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/DeploymentsClient", "CheckExistence", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.DeploymentsClient", "CheckExistence", resp, "Failure responding to request") } return @@ -152,7 +153,7 @@ func (client DeploymentsClient) CheckExistencePreparer(resourceGroupName string, // CheckExistenceSender sends the CheckExistence request. The method will close the // http.Response Body if it receives an error. func (client DeploymentsClient) CheckExistenceSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusNoContent, http.StatusNotFound) + return autorest.SendWithSender(client, req) } // CheckExistenceResponder handles the response to the CheckExistence request. The method always @@ -161,39 +162,42 @@ func (client DeploymentsClient) CheckExistenceResponder(resp *http.Response) (re err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent, http.StatusNotFound), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent, http.StatusNotFound), autorest.ByClosing()) result.Response = resp return } -// CreateOrUpdate create a named template deployment using a template. +// CreateOrUpdate create a named template deployment using a template. This +// method may poll for completion. Polling can be canceled by passing the +// cancel channel argument. The channel will be used to cancel polling and +// any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. The name is case // insensitive. deploymentName is the name of the deployment. parameters is // additional parameters supplied to the operation. -func (client DeploymentsClient) CreateOrUpdate(resourceGroupName string, deploymentName string, parameters Deployment) (result DeploymentExtended, ae error) { - req, err := client.CreateOrUpdatePreparer(resourceGroupName, deploymentName, parameters) +func (client DeploymentsClient) CreateOrUpdate(resourceGroupName string, deploymentName string, parameters Deployment, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, deploymentName, parameters, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/DeploymentsClient", "CreateOrUpdate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.DeploymentsClient", "CreateOrUpdate", nil, "Failure preparing request") } resp, err := client.CreateOrUpdateSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/DeploymentsClient", "CreateOrUpdate", resp.StatusCode, "Failure sending request") + result.Response = resp + return result, autorest.NewErrorWithError(err, "resources.DeploymentsClient", "CreateOrUpdate", resp, "Failure sending request") } result, err = client.CreateOrUpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/DeploymentsClient", "CreateOrUpdate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.DeploymentsClient", "CreateOrUpdate", resp, "Failure responding to request") } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client DeploymentsClient) CreateOrUpdatePreparer(resourceGroupName string, deploymentName string, parameters Deployment) (*http.Request, error) { +func (client DeploymentsClient) CreateOrUpdatePreparer(resourceGroupName string, deploymentName string, parameters Deployment, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "deploymentName": url.QueryEscape(deploymentName), "resourceGroupName": url.QueryEscape(resourceGroupName), @@ -204,7 +208,7 @@ func (client DeploymentsClient) CreateOrUpdatePreparer(resourceGroupName string, "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), @@ -217,49 +221,53 @@ func (client DeploymentsClient) CreateOrUpdatePreparer(resourceGroupName string, // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client DeploymentsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusCreated) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client DeploymentsClient) CreateOrUpdateResponder(resp *http.Response) (result DeploymentExtended, err error) { +func (client DeploymentsClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + result.Response = resp return } // Delete begin deleting deployment.To determine whether the operation has -// finished processing the request, call GetLongRunningOperationStatus. +// finished processing the request, call GetLongRunningOperationStatus. This +// method may poll for completion. Polling can be canceled by passing the +// cancel channel argument. The channel will be used to cancel polling and +// any outstanding HTTP requests. // // resourceGroupName is the name of the resource group. The name is case // insensitive. deploymentName is the name of the deployment to be deleted. -func (client DeploymentsClient) Delete(resourceGroupName string, deploymentName string) (result autorest.Response, ae error) { - req, err := client.DeletePreparer(resourceGroupName, deploymentName) +func (client DeploymentsClient) Delete(resourceGroupName string, deploymentName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, deploymentName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/DeploymentsClient", "Delete", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.DeploymentsClient", "Delete", nil, "Failure preparing request") } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "resources/DeploymentsClient", "Delete", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.DeploymentsClient", "Delete", resp, "Failure sending request") } result, err = client.DeleteResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/DeploymentsClient", "Delete", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.DeploymentsClient", "Delete", resp, "Failure responding to request") } return } // DeletePreparer prepares the Delete request. -func (client DeploymentsClient) DeletePreparer(resourceGroupName string, deploymentName string) (*http.Request, error) { +func (client DeploymentsClient) DeletePreparer(resourceGroupName string, deploymentName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "deploymentName": url.QueryEscape(deploymentName), "resourceGroupName": url.QueryEscape(resourceGroupName), @@ -270,7 +278,7 @@ func (client DeploymentsClient) DeletePreparer(resourceGroupName string, deploym "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), @@ -282,7 +290,9 @@ func (client DeploymentsClient) DeletePreparer(resourceGroupName string, deploym // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client DeploymentsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted, http.StatusNoContent) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // DeleteResponder handles the response to the Delete request. The method always @@ -291,7 +301,7 @@ func (client DeploymentsClient) DeleteResponder(resp *http.Response) (result aut err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return @@ -301,21 +311,21 @@ func (client DeploymentsClient) DeleteResponder(resp *http.Response) (result aut // // resourceGroupName is the name of the resource group to get. The name is // case insensitive. deploymentName is the name of the deployment. -func (client DeploymentsClient) Get(resourceGroupName string, deploymentName string) (result DeploymentExtended, ae error) { +func (client DeploymentsClient) Get(resourceGroupName string, deploymentName string) (result DeploymentExtended, err error) { req, err := client.GetPreparer(resourceGroupName, deploymentName) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/DeploymentsClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.DeploymentsClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/DeploymentsClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.DeploymentsClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/DeploymentsClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.DeploymentsClient", "Get", resp, "Failure responding to request") } return @@ -345,7 +355,7 @@ func (client DeploymentsClient) GetPreparer(resourceGroupName string, deployment // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client DeploymentsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -354,7 +364,7 @@ func (client DeploymentsClient) GetResponder(resp *http.Response) (result Deploy err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -366,28 +376,28 @@ func (client DeploymentsClient) GetResponder(resp *http.Response) (result Deploy // resourceGroupName is the name of the resource group to filter by. The name // is case insensitive. filter is the filter to apply on the operation. top // is query parameters. If null is passed returns all deployments. -func (client DeploymentsClient) List(resourceGroupName string, filter string, top *int) (result DeploymentListResult, ae error) { +func (client DeploymentsClient) List(resourceGroupName string, filter string, top *int32) (result DeploymentListResult, err error) { req, err := client.ListPreparer(resourceGroupName, filter, top) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/DeploymentsClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.DeploymentsClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/DeploymentsClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.DeploymentsClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/DeploymentsClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.DeploymentsClient", "List", resp, "Failure responding to request") } return } // ListPreparer prepares the List request. -func (client DeploymentsClient) ListPreparer(resourceGroupName string, filter string, top *int) (*http.Request, error) { +func (client DeploymentsClient) ListPreparer(resourceGroupName string, filter string, top *int32) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "subscriptionId": url.QueryEscape(client.SubscriptionID), @@ -415,7 +425,7 @@ func (client DeploymentsClient) ListPreparer(resourceGroupName string, filter st // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client DeploymentsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -424,7 +434,7 @@ func (client DeploymentsClient) ListResponder(resp *http.Response) (result Deplo err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -432,10 +442,10 @@ func (client DeploymentsClient) ListResponder(resp *http.Response) (result Deplo } // ListNextResults retrieves the next set of results, if any. -func (client DeploymentsClient) ListNextResults(lastResults DeploymentListResult) (result DeploymentListResult, ae error) { +func (client DeploymentsClient) ListNextResults(lastResults DeploymentListResult) (result DeploymentListResult, err error) { req, err := lastResults.DeploymentListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "resources/DeploymentsClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "resources.DeploymentsClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -444,12 +454,12 @@ func (client DeploymentsClient) ListNextResults(lastResults DeploymentListResult resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/DeploymentsClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "resources.DeploymentsClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/DeploymentsClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "resources.DeploymentsClient", "List", resp, "Failure responding to next results request request") } return @@ -460,21 +470,21 @@ func (client DeploymentsClient) ListNextResults(lastResults DeploymentListResult // resourceGroupName is the name of the resource group. The name is case // insensitive. deploymentName is the name of the deployment. parameters is // deployment to validate. -func (client DeploymentsClient) Validate(resourceGroupName string, deploymentName string, parameters Deployment) (result DeploymentValidateResult, ae error) { +func (client DeploymentsClient) Validate(resourceGroupName string, deploymentName string, parameters Deployment) (result DeploymentValidateResult, err error) { req, err := client.ValidatePreparer(resourceGroupName, deploymentName, parameters) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/DeploymentsClient", "Validate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.DeploymentsClient", "Validate", nil, "Failure preparing request") } resp, err := client.ValidateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/DeploymentsClient", "Validate", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.DeploymentsClient", "Validate", resp, "Failure sending request") } result, err = client.ValidateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/DeploymentsClient", "Validate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.DeploymentsClient", "Validate", resp, "Failure responding to request") } return @@ -505,7 +515,7 @@ func (client DeploymentsClient) ValidatePreparer(resourceGroupName string, deplo // ValidateSender sends the Validate request. The method will close the // http.Response Body if it receives an error. func (client DeploymentsClient) ValidateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusBadRequest) + return autorest.SendWithSender(client, req) } // ValidateResponder handles the response to the Validate request. The method always @@ -514,7 +524,7 @@ func (client DeploymentsClient) ValidateResponder(resp *http.Response) (result D err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusBadRequest), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusBadRequest), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/groups.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/groups.go index 785cf0dffd12..aa874d97a725 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/groups.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/groups.go @@ -14,12 +14,13 @@ package resources // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -43,21 +44,21 @@ func NewGroupsClientWithBaseURI(baseURI string, subscriptionID string) GroupsCli // // resourceGroupName is the name of the resource group to check. The name is // case insensitive. -func (client GroupsClient) CheckExistence(resourceGroupName string) (result autorest.Response, ae error) { +func (client GroupsClient) CheckExistence(resourceGroupName string) (result autorest.Response, err error) { req, err := client.CheckExistencePreparer(resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/GroupsClient", "CheckExistence", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.GroupsClient", "CheckExistence", nil, "Failure preparing request") } resp, err := client.CheckExistenceSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "resources/GroupsClient", "CheckExistence", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.GroupsClient", "CheckExistence", resp, "Failure sending request") } result, err = client.CheckExistenceResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/GroupsClient", "CheckExistence", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.GroupsClient", "CheckExistence", resp, "Failure responding to request") } return @@ -86,7 +87,7 @@ func (client GroupsClient) CheckExistencePreparer(resourceGroupName string) (*ht // CheckExistenceSender sends the CheckExistence request. The method will close the // http.Response Body if it receives an error. func (client GroupsClient) CheckExistenceSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusNoContent, http.StatusNotFound) + return autorest.SendWithSender(client, req) } // CheckExistenceResponder handles the response to the CheckExistence request. The method always @@ -95,7 +96,7 @@ func (client GroupsClient) CheckExistenceResponder(resp *http.Response) (result err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent, http.StatusNotFound), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent, http.StatusNotFound), autorest.ByClosing()) result.Response = resp return @@ -106,21 +107,21 @@ func (client GroupsClient) CheckExistenceResponder(resp *http.Response) (result // resourceGroupName is the name of the resource group to be created or // updated. parameters is parameters supplied to the create or update // resource group service operation. -func (client GroupsClient) CreateOrUpdate(resourceGroupName string, parameters ResourceGroup) (result ResourceGroup, ae error) { +func (client GroupsClient) CreateOrUpdate(resourceGroupName string, parameters ResourceGroup) (result ResourceGroup, err error) { req, err := client.CreateOrUpdatePreparer(resourceGroupName, parameters) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/GroupsClient", "CreateOrUpdate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.GroupsClient", "CreateOrUpdate", nil, "Failure preparing request") } resp, err := client.CreateOrUpdateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/GroupsClient", "CreateOrUpdate", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.GroupsClient", "CreateOrUpdate", resp, "Failure sending request") } result, err = client.CreateOrUpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/GroupsClient", "CreateOrUpdate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.GroupsClient", "CreateOrUpdate", resp, "Failure responding to request") } return @@ -150,7 +151,7 @@ func (client GroupsClient) CreateOrUpdatePreparer(resourceGroupName string, para // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client GroupsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusCreated, http.StatusOK) + return autorest.SendWithSender(client, req) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always @@ -159,7 +160,7 @@ func (client GroupsClient) CreateOrUpdateResponder(resp *http.Response) (result err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -167,32 +168,35 @@ func (client GroupsClient) CreateOrUpdateResponder(resp *http.Response) (result } // Delete begin deleting resource group.To determine whether the operation has -// finished processing the request, call GetLongRunningOperationStatus. +// finished processing the request, call GetLongRunningOperationStatus. This +// method may poll for completion. Polling can be canceled by passing the +// cancel channel argument. The channel will be used to cancel polling and +// any outstanding HTTP requests. // // resourceGroupName is the name of the resource group to be deleted. The name // is case insensitive. -func (client GroupsClient) Delete(resourceGroupName string) (result autorest.Response, ae error) { - req, err := client.DeletePreparer(resourceGroupName) +func (client GroupsClient) Delete(resourceGroupName string, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.DeletePreparer(resourceGroupName, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/GroupsClient", "Delete", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.GroupsClient", "Delete", nil, "Failure preparing request") } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "resources/GroupsClient", "Delete", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.GroupsClient", "Delete", resp, "Failure sending request") } result, err = client.DeleteResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/GroupsClient", "Delete", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.GroupsClient", "Delete", resp, "Failure responding to request") } return } // DeletePreparer prepares the Delete request. -func (client GroupsClient) DeletePreparer(resourceGroupName string) (*http.Request, error) { +func (client GroupsClient) DeletePreparer(resourceGroupName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "subscriptionId": url.QueryEscape(client.SubscriptionID), @@ -202,7 +206,7 @@ func (client GroupsClient) DeletePreparer(resourceGroupName string) (*http.Reque "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), @@ -214,7 +218,9 @@ func (client GroupsClient) DeletePreparer(resourceGroupName string) (*http.Reque // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client GroupsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusAccepted, http.StatusOK) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // DeleteResponder handles the response to the Delete request. The method always @@ -223,7 +229,7 @@ func (client GroupsClient) DeleteResponder(resp *http.Response) (result autorest err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusOK), autorest.ByClosing()) result.Response = resp return @@ -233,21 +239,21 @@ func (client GroupsClient) DeleteResponder(resp *http.Response) (result autorest // // resourceGroupName is the name of the resource group to get. The name is // case insensitive. -func (client GroupsClient) Get(resourceGroupName string) (result ResourceGroup, ae error) { +func (client GroupsClient) Get(resourceGroupName string) (result ResourceGroup, err error) { req, err := client.GetPreparer(resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/GroupsClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.GroupsClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/GroupsClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.GroupsClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/GroupsClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.GroupsClient", "Get", resp, "Failure responding to request") } return @@ -276,7 +282,7 @@ func (client GroupsClient) GetPreparer(resourceGroupName string) (*http.Request, // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client GroupsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -285,7 +291,7 @@ func (client GroupsClient) GetResponder(resp *http.Response) (result ResourceGro err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -296,28 +302,28 @@ func (client GroupsClient) GetResponder(resp *http.Response) (result ResourceGro // // filter is the filter to apply on the operation. top is query parameters. If // null is passed returns all resource groups. -func (client GroupsClient) List(filter string, top *int) (result ResourceGroupListResult, ae error) { +func (client GroupsClient) List(filter string, top *int32) (result ResourceGroupListResult, err error) { req, err := client.ListPreparer(filter, top) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/GroupsClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.GroupsClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/GroupsClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.GroupsClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/GroupsClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.GroupsClient", "List", resp, "Failure responding to request") } return } // ListPreparer prepares the List request. -func (client GroupsClient) ListPreparer(filter string, top *int) (*http.Request, error) { +func (client GroupsClient) ListPreparer(filter string, top *int32) (*http.Request, error) { pathParameters := map[string]interface{}{ "subscriptionId": url.QueryEscape(client.SubscriptionID), } @@ -344,7 +350,7 @@ func (client GroupsClient) ListPreparer(filter string, top *int) (*http.Request, // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client GroupsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -353,7 +359,7 @@ func (client GroupsClient) ListResponder(resp *http.Response) (result ResourceGr err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -361,10 +367,10 @@ func (client GroupsClient) ListResponder(resp *http.Response) (result ResourceGr } // ListNextResults retrieves the next set of results, if any. -func (client GroupsClient) ListNextResults(lastResults ResourceGroupListResult) (result ResourceGroupListResult, ae error) { +func (client GroupsClient) ListNextResults(lastResults ResourceGroupListResult) (result ResourceGroupListResult, err error) { req, err := lastResults.ResourceGroupListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "resources/GroupsClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "resources.GroupsClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -373,12 +379,12 @@ func (client GroupsClient) ListNextResults(lastResults ResourceGroupListResult) resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/GroupsClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "resources.GroupsClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/GroupsClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "resources.GroupsClient", "List", resp, "Failure responding to next results request request") } return @@ -389,28 +395,28 @@ func (client GroupsClient) ListNextResults(lastResults ResourceGroupListResult) // resourceGroupName is query parameters. If null is passed returns all // resource groups. filter is the filter to apply on the operation. top is // query parameters. If null is passed returns all resource groups. -func (client GroupsClient) ListResources(resourceGroupName string, filter string, top *int) (result ResourceListResult, ae error) { +func (client GroupsClient) ListResources(resourceGroupName string, filter string, top *int32) (result ResourceListResult, err error) { req, err := client.ListResourcesPreparer(resourceGroupName, filter, top) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/GroupsClient", "ListResources", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.GroupsClient", "ListResources", nil, "Failure preparing request") } resp, err := client.ListResourcesSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/GroupsClient", "ListResources", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.GroupsClient", "ListResources", resp, "Failure sending request") } result, err = client.ListResourcesResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/GroupsClient", "ListResources", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.GroupsClient", "ListResources", resp, "Failure responding to request") } return } // ListResourcesPreparer prepares the ListResources request. -func (client GroupsClient) ListResourcesPreparer(resourceGroupName string, filter string, top *int) (*http.Request, error) { +func (client GroupsClient) ListResourcesPreparer(resourceGroupName string, filter string, top *int32) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": url.QueryEscape(resourceGroupName), "subscriptionId": url.QueryEscape(client.SubscriptionID), @@ -438,7 +444,7 @@ func (client GroupsClient) ListResourcesPreparer(resourceGroupName string, filte // ListResourcesSender sends the ListResources request. The method will close the // http.Response Body if it receives an error. func (client GroupsClient) ListResourcesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResourcesResponder handles the response to the ListResources request. The method always @@ -447,7 +453,7 @@ func (client GroupsClient) ListResourcesResponder(resp *http.Response) (result R err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -455,10 +461,10 @@ func (client GroupsClient) ListResourcesResponder(resp *http.Response) (result R } // ListResourcesNextResults retrieves the next set of results, if any. -func (client GroupsClient) ListResourcesNextResults(lastResults ResourceListResult) (result ResourceListResult, ae error) { +func (client GroupsClient) ListResourcesNextResults(lastResults ResourceListResult) (result ResourceListResult, err error) { req, err := lastResults.ResourceListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "resources/GroupsClient", "ListResources", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "resources.GroupsClient", "ListResources", nil, "Failure preparing next results request request") } if req == nil { return @@ -467,12 +473,12 @@ func (client GroupsClient) ListResourcesNextResults(lastResults ResourceListResu resp, err := client.ListResourcesSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/GroupsClient", "ListResources", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "resources.GroupsClient", "ListResources", resp, "Failure sending next results request request") } result, err = client.ListResourcesResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/GroupsClient", "ListResources", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "resources.GroupsClient", "ListResources", resp, "Failure responding to next results request request") } return @@ -486,21 +492,21 @@ func (client GroupsClient) ListResourcesNextResults(lastResults ResourceListResu // resourceGroupName is the name of the resource group to be created or // updated. The name is case insensitive. parameters is parameters supplied // to the update state resource group service operation. -func (client GroupsClient) Patch(resourceGroupName string, parameters ResourceGroup) (result ResourceGroup, ae error) { +func (client GroupsClient) Patch(resourceGroupName string, parameters ResourceGroup) (result ResourceGroup, err error) { req, err := client.PatchPreparer(resourceGroupName, parameters) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/GroupsClient", "Patch", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.GroupsClient", "Patch", nil, "Failure preparing request") } resp, err := client.PatchSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/GroupsClient", "Patch", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.GroupsClient", "Patch", resp, "Failure sending request") } result, err = client.PatchResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/GroupsClient", "Patch", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.GroupsClient", "Patch", resp, "Failure responding to request") } return @@ -530,7 +536,7 @@ func (client GroupsClient) PatchPreparer(resourceGroupName string, parameters Re // PatchSender sends the Patch request. The method will close the // http.Response Body if it receives an error. func (client GroupsClient) PatchSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // PatchResponder handles the response to the Patch request. The method always @@ -539,7 +545,7 @@ func (client GroupsClient) PatchResponder(resp *http.Response) (result ResourceG err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/models.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/models.go index 754edbb5e658..dddb3adaecc3 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/models.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/models.go @@ -14,14 +14,14 @@ package resources // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/date" - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/to" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/date" + "github.com/Azure/go-autorest/autorest/to" "net/http" ) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/policyassignments.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/policyassignments.go index e45d2d7f1b0e..7233c2bd394e 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/policyassignments.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/policyassignments.go @@ -14,12 +14,13 @@ package resources // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -46,21 +47,21 @@ func NewPolicyAssignmentsClientWithBaseURI(baseURI string, subscriptionID string // // scope is scope. policyAssignmentName is policy assignment name. parameters // is policy assignment. -func (client PolicyAssignmentsClient) Create(scope string, policyAssignmentName string, parameters PolicyAssignment) (result PolicyAssignment, ae error) { +func (client PolicyAssignmentsClient) Create(scope string, policyAssignmentName string, parameters PolicyAssignment) (result PolicyAssignment, err error) { req, err := client.CreatePreparer(scope, policyAssignmentName, parameters) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "Create", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "Create", nil, "Failure preparing request") } resp, err := client.CreateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "Create", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "Create", resp, "Failure sending request") } result, err = client.CreateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "Create", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "Create", resp, "Failure responding to request") } return @@ -91,7 +92,7 @@ func (client PolicyAssignmentsClient) CreatePreparer(scope string, policyAssignm // CreateSender sends the Create request. The method will close the // http.Response Body if it receives an error. func (client PolicyAssignmentsClient) CreateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusCreated) + return autorest.SendWithSender(client, req) } // CreateResponder handles the response to the Create request. The method always @@ -100,7 +101,7 @@ func (client PolicyAssignmentsClient) CreateResponder(resp *http.Response) (resu err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -110,21 +111,21 @@ func (client PolicyAssignmentsClient) CreateResponder(resp *http.Response) (resu // CreateByID create policy assignment by Id. // // policyAssignmentID is policy assignment Id parameters is policy assignment. -func (client PolicyAssignmentsClient) CreateByID(policyAssignmentID string, parameters PolicyAssignment) (result PolicyAssignment, ae error) { +func (client PolicyAssignmentsClient) CreateByID(policyAssignmentID string, parameters PolicyAssignment) (result PolicyAssignment, err error) { req, err := client.CreateByIDPreparer(policyAssignmentID, parameters) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "CreateByID", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "CreateByID", nil, "Failure preparing request") } resp, err := client.CreateByIDSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "CreateByID", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "CreateByID", resp, "Failure sending request") } result, err = client.CreateByIDResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "CreateByID", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "CreateByID", resp, "Failure responding to request") } return @@ -154,7 +155,7 @@ func (client PolicyAssignmentsClient) CreateByIDPreparer(policyAssignmentID stri // CreateByIDSender sends the CreateByID request. The method will close the // http.Response Body if it receives an error. func (client PolicyAssignmentsClient) CreateByIDSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusCreated) + return autorest.SendWithSender(client, req) } // CreateByIDResponder handles the response to the CreateByID request. The method always @@ -163,7 +164,7 @@ func (client PolicyAssignmentsClient) CreateByIDResponder(resp *http.Response) ( err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -173,21 +174,21 @@ func (client PolicyAssignmentsClient) CreateByIDResponder(resp *http.Response) ( // Delete delete policy assignment. // // scope is scope. policyAssignmentName is policy assignment name. -func (client PolicyAssignmentsClient) Delete(scope string, policyAssignmentName string) (result PolicyAssignment, ae error) { +func (client PolicyAssignmentsClient) Delete(scope string, policyAssignmentName string) (result PolicyAssignment, err error) { req, err := client.DeletePreparer(scope, policyAssignmentName) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "Delete", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "Delete", nil, "Failure preparing request") } resp, err := client.DeleteSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "Delete", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "Delete", resp, "Failure sending request") } result, err = client.DeleteResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "Delete", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "Delete", resp, "Failure responding to request") } return @@ -217,7 +218,7 @@ func (client PolicyAssignmentsClient) DeletePreparer(scope string, policyAssignm // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client PolicyAssignmentsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // DeleteResponder handles the response to the Delete request. The method always @@ -226,7 +227,7 @@ func (client PolicyAssignmentsClient) DeleteResponder(resp *http.Response) (resu err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -236,21 +237,21 @@ func (client PolicyAssignmentsClient) DeleteResponder(resp *http.Response) (resu // DeleteByID delete policy assignment. // // policyAssignmentID is policy assignment Id -func (client PolicyAssignmentsClient) DeleteByID(policyAssignmentID string) (result PolicyAssignment, ae error) { +func (client PolicyAssignmentsClient) DeleteByID(policyAssignmentID string) (result PolicyAssignment, err error) { req, err := client.DeleteByIDPreparer(policyAssignmentID) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "DeleteByID", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "DeleteByID", nil, "Failure preparing request") } resp, err := client.DeleteByIDSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "DeleteByID", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "DeleteByID", resp, "Failure sending request") } result, err = client.DeleteByIDResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "DeleteByID", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "DeleteByID", resp, "Failure responding to request") } return @@ -279,7 +280,7 @@ func (client PolicyAssignmentsClient) DeleteByIDPreparer(policyAssignmentID stri // DeleteByIDSender sends the DeleteByID request. The method will close the // http.Response Body if it receives an error. func (client PolicyAssignmentsClient) DeleteByIDSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // DeleteByIDResponder handles the response to the DeleteByID request. The method always @@ -288,7 +289,7 @@ func (client PolicyAssignmentsClient) DeleteByIDResponder(resp *http.Response) ( err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -298,21 +299,21 @@ func (client PolicyAssignmentsClient) DeleteByIDResponder(resp *http.Response) ( // Get get single policy assignment. // // scope is scope. policyAssignmentName is policy assignment name. -func (client PolicyAssignmentsClient) Get(scope string, policyAssignmentName string) (result PolicyAssignment, ae error) { +func (client PolicyAssignmentsClient) Get(scope string, policyAssignmentName string) (result PolicyAssignment, err error) { req, err := client.GetPreparer(scope, policyAssignmentName) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "Get", resp, "Failure responding to request") } return @@ -342,7 +343,7 @@ func (client PolicyAssignmentsClient) GetPreparer(scope string, policyAssignment // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client PolicyAssignmentsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -351,7 +352,7 @@ func (client PolicyAssignmentsClient) GetResponder(resp *http.Response) (result err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -361,21 +362,21 @@ func (client PolicyAssignmentsClient) GetResponder(resp *http.Response) (result // GetByID get single policy assignment. // // policyAssignmentID is policy assignment Id -func (client PolicyAssignmentsClient) GetByID(policyAssignmentID string) (result PolicyAssignment, ae error) { +func (client PolicyAssignmentsClient) GetByID(policyAssignmentID string) (result PolicyAssignment, err error) { req, err := client.GetByIDPreparer(policyAssignmentID) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "GetByID", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "GetByID", nil, "Failure preparing request") } resp, err := client.GetByIDSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "GetByID", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "GetByID", resp, "Failure sending request") } result, err = client.GetByIDResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "GetByID", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "GetByID", resp, "Failure responding to request") } return @@ -404,7 +405,7 @@ func (client PolicyAssignmentsClient) GetByIDPreparer(policyAssignmentID string) // GetByIDSender sends the GetByID request. The method will close the // http.Response Body if it receives an error. func (client PolicyAssignmentsClient) GetByIDSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetByIDResponder handles the response to the GetByID request. The method always @@ -413,7 +414,7 @@ func (client PolicyAssignmentsClient) GetByIDResponder(resp *http.Response) (res err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -423,21 +424,21 @@ func (client PolicyAssignmentsClient) GetByIDResponder(resp *http.Response) (res // List gets policy assignments of the subscription. // // filter is the filter to apply on the operation. -func (client PolicyAssignmentsClient) List(filter string) (result PolicyAssignmentListResult, ae error) { +func (client PolicyAssignmentsClient) List(filter string) (result PolicyAssignmentListResult, err error) { req, err := client.ListPreparer(filter) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "List", resp, "Failure responding to request") } return @@ -468,7 +469,7 @@ func (client PolicyAssignmentsClient) ListPreparer(filter string) (*http.Request // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client PolicyAssignmentsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -477,7 +478,7 @@ func (client PolicyAssignmentsClient) ListResponder(resp *http.Response) (result err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -485,10 +486,10 @@ func (client PolicyAssignmentsClient) ListResponder(resp *http.Response) (result } // ListNextResults retrieves the next set of results, if any. -func (client PolicyAssignmentsClient) ListNextResults(lastResults PolicyAssignmentListResult) (result PolicyAssignmentListResult, ae error) { +func (client PolicyAssignmentsClient) ListNextResults(lastResults PolicyAssignmentListResult) (result PolicyAssignmentListResult, err error) { req, err := lastResults.PolicyAssignmentListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -497,12 +498,12 @@ func (client PolicyAssignmentsClient) ListNextResults(lastResults PolicyAssignme resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "List", resp, "Failure responding to next results request request") } return @@ -515,21 +516,21 @@ func (client PolicyAssignmentsClient) ListNextResults(lastResults PolicyAssignme // parentResourcePath is the parent resource path. resourceType is the // resource type. resourceName is the resource name. filter is the filter to // apply on the operation. -func (client PolicyAssignmentsClient) ListForResource(resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, filter string) (result PolicyAssignmentListResult, ae error) { +func (client PolicyAssignmentsClient) ListForResource(resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, filter string) (result PolicyAssignmentListResult, err error) { req, err := client.ListForResourcePreparer(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, filter) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "ListForResource", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "ListForResource", nil, "Failure preparing request") } resp, err := client.ListForResourceSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "ListForResource", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "ListForResource", resp, "Failure sending request") } result, err = client.ListForResourceResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "ListForResource", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "ListForResource", resp, "Failure responding to request") } return @@ -565,7 +566,7 @@ func (client PolicyAssignmentsClient) ListForResourcePreparer(resourceGroupName // ListForResourceSender sends the ListForResource request. The method will close the // http.Response Body if it receives an error. func (client PolicyAssignmentsClient) ListForResourceSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListForResourceResponder handles the response to the ListForResource request. The method always @@ -574,7 +575,7 @@ func (client PolicyAssignmentsClient) ListForResourceResponder(resp *http.Respon err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -582,10 +583,10 @@ func (client PolicyAssignmentsClient) ListForResourceResponder(resp *http.Respon } // ListForResourceNextResults retrieves the next set of results, if any. -func (client PolicyAssignmentsClient) ListForResourceNextResults(lastResults PolicyAssignmentListResult) (result PolicyAssignmentListResult, ae error) { +func (client PolicyAssignmentsClient) ListForResourceNextResults(lastResults PolicyAssignmentListResult) (result PolicyAssignmentListResult, err error) { req, err := lastResults.PolicyAssignmentListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "ListForResource", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "ListForResource", nil, "Failure preparing next results request request") } if req == nil { return @@ -594,12 +595,12 @@ func (client PolicyAssignmentsClient) ListForResourceNextResults(lastResults Pol resp, err := client.ListForResourceSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "ListForResource", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "ListForResource", resp, "Failure sending next results request request") } result, err = client.ListForResourceResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "ListForResource", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "ListForResource", resp, "Failure responding to next results request request") } return @@ -609,21 +610,21 @@ func (client PolicyAssignmentsClient) ListForResourceNextResults(lastResults Pol // // resourceGroupName is resource group name. filter is the filter to apply on // the operation. -func (client PolicyAssignmentsClient) ListForResourceGroup(resourceGroupName string, filter string) (result PolicyAssignmentListResult, ae error) { +func (client PolicyAssignmentsClient) ListForResourceGroup(resourceGroupName string, filter string) (result PolicyAssignmentListResult, err error) { req, err := client.ListForResourceGroupPreparer(resourceGroupName, filter) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "ListForResourceGroup", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "ListForResourceGroup", nil, "Failure preparing request") } resp, err := client.ListForResourceGroupSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "ListForResourceGroup", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "ListForResourceGroup", resp, "Failure sending request") } result, err = client.ListForResourceGroupResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "ListForResourceGroup", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "ListForResourceGroup", resp, "Failure responding to request") } return @@ -655,7 +656,7 @@ func (client PolicyAssignmentsClient) ListForResourceGroupPreparer(resourceGroup // ListForResourceGroupSender sends the ListForResourceGroup request. The method will close the // http.Response Body if it receives an error. func (client PolicyAssignmentsClient) ListForResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListForResourceGroupResponder handles the response to the ListForResourceGroup request. The method always @@ -664,7 +665,7 @@ func (client PolicyAssignmentsClient) ListForResourceGroupResponder(resp *http.R err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -672,10 +673,10 @@ func (client PolicyAssignmentsClient) ListForResourceGroupResponder(resp *http.R } // ListForResourceGroupNextResults retrieves the next set of results, if any. -func (client PolicyAssignmentsClient) ListForResourceGroupNextResults(lastResults PolicyAssignmentListResult) (result PolicyAssignmentListResult, ae error) { +func (client PolicyAssignmentsClient) ListForResourceGroupNextResults(lastResults PolicyAssignmentListResult) (result PolicyAssignmentListResult, err error) { req, err := lastResults.PolicyAssignmentListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "ListForResourceGroup", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "ListForResourceGroup", nil, "Failure preparing next results request request") } if req == nil { return @@ -684,12 +685,12 @@ func (client PolicyAssignmentsClient) ListForResourceGroupNextResults(lastResult resp, err := client.ListForResourceGroupSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "ListForResourceGroup", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "ListForResourceGroup", resp, "Failure sending next results request request") } result, err = client.ListForResourceGroupResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "ListForResourceGroup", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "ListForResourceGroup", resp, "Failure responding to next results request request") } return @@ -698,21 +699,21 @@ func (client PolicyAssignmentsClient) ListForResourceGroupNextResults(lastResult // ListForScope gets policy assignments of the scope. // // scope is scope. filter is the filter to apply on the operation. -func (client PolicyAssignmentsClient) ListForScope(scope string, filter string) (result PolicyAssignmentListResult, ae error) { +func (client PolicyAssignmentsClient) ListForScope(scope string, filter string) (result PolicyAssignmentListResult, err error) { req, err := client.ListForScopePreparer(scope, filter) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "ListForScope", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "ListForScope", nil, "Failure preparing request") } resp, err := client.ListForScopeSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "ListForScope", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "ListForScope", resp, "Failure sending request") } result, err = client.ListForScopeResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "ListForScope", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "ListForScope", resp, "Failure responding to request") } return @@ -744,7 +745,7 @@ func (client PolicyAssignmentsClient) ListForScopePreparer(scope string, filter // ListForScopeSender sends the ListForScope request. The method will close the // http.Response Body if it receives an error. func (client PolicyAssignmentsClient) ListForScopeSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListForScopeResponder handles the response to the ListForScope request. The method always @@ -753,7 +754,7 @@ func (client PolicyAssignmentsClient) ListForScopeResponder(resp *http.Response) err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -761,10 +762,10 @@ func (client PolicyAssignmentsClient) ListForScopeResponder(resp *http.Response) } // ListForScopeNextResults retrieves the next set of results, if any. -func (client PolicyAssignmentsClient) ListForScopeNextResults(lastResults PolicyAssignmentListResult) (result PolicyAssignmentListResult, ae error) { +func (client PolicyAssignmentsClient) ListForScopeNextResults(lastResults PolicyAssignmentListResult) (result PolicyAssignmentListResult, err error) { req, err := lastResults.PolicyAssignmentListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "ListForScope", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "ListForScope", nil, "Failure preparing next results request request") } if req == nil { return @@ -773,12 +774,12 @@ func (client PolicyAssignmentsClient) ListForScopeNextResults(lastResults Policy resp, err := client.ListForScopeSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "ListForScope", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "ListForScope", resp, "Failure sending next results request request") } result, err = client.ListForScopeResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/PolicyAssignmentsClient", "ListForScope", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "resources.PolicyAssignmentsClient", "ListForScope", resp, "Failure responding to next results request request") } return diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/policydefinitions.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/policydefinitions.go index 25f740d2efe6..0251447ed6ae 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/policydefinitions.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/policydefinitions.go @@ -14,12 +14,13 @@ package resources // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -46,21 +47,21 @@ func NewPolicyDefinitionsClientWithBaseURI(baseURI string, subscriptionID string // // policyDefinitionName is the policy definition name. parameters is the // policy definition properties -func (client PolicyDefinitionsClient) CreateOrUpdate(policyDefinitionName string, parameters PolicyDefinition) (result PolicyDefinition, ae error) { +func (client PolicyDefinitionsClient) CreateOrUpdate(policyDefinitionName string, parameters PolicyDefinition) (result PolicyDefinition, err error) { req, err := client.CreateOrUpdatePreparer(policyDefinitionName, parameters) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/PolicyDefinitionsClient", "CreateOrUpdate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.PolicyDefinitionsClient", "CreateOrUpdate", nil, "Failure preparing request") } resp, err := client.CreateOrUpdateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/PolicyDefinitionsClient", "CreateOrUpdate", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.PolicyDefinitionsClient", "CreateOrUpdate", resp, "Failure sending request") } result, err = client.CreateOrUpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/PolicyDefinitionsClient", "CreateOrUpdate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.PolicyDefinitionsClient", "CreateOrUpdate", resp, "Failure responding to request") } return @@ -90,7 +91,7 @@ func (client PolicyDefinitionsClient) CreateOrUpdatePreparer(policyDefinitionNam // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client PolicyDefinitionsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusCreated) + return autorest.SendWithSender(client, req) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always @@ -99,7 +100,7 @@ func (client PolicyDefinitionsClient) CreateOrUpdateResponder(resp *http.Respons err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -109,21 +110,21 @@ func (client PolicyDefinitionsClient) CreateOrUpdateResponder(resp *http.Respons // Delete deletes policy definition. // // policyDefinitionName is the policy definition name. -func (client PolicyDefinitionsClient) Delete(policyDefinitionName string) (result autorest.Response, ae error) { +func (client PolicyDefinitionsClient) Delete(policyDefinitionName string) (result autorest.Response, err error) { req, err := client.DeletePreparer(policyDefinitionName) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/PolicyDefinitionsClient", "Delete", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.PolicyDefinitionsClient", "Delete", nil, "Failure preparing request") } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "resources/PolicyDefinitionsClient", "Delete", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.PolicyDefinitionsClient", "Delete", resp, "Failure sending request") } result, err = client.DeleteResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/PolicyDefinitionsClient", "Delete", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.PolicyDefinitionsClient", "Delete", resp, "Failure responding to request") } return @@ -152,7 +153,7 @@ func (client PolicyDefinitionsClient) DeletePreparer(policyDefinitionName string // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client PolicyDefinitionsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // DeleteResponder handles the response to the Delete request. The method always @@ -161,7 +162,7 @@ func (client PolicyDefinitionsClient) DeleteResponder(resp *http.Response) (resu err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByClosing()) result.Response = resp return @@ -170,21 +171,21 @@ func (client PolicyDefinitionsClient) DeleteResponder(resp *http.Response) (resu // Get gets policy definition. // // policyDefinitionName is the policy definition name. -func (client PolicyDefinitionsClient) Get(policyDefinitionName string) (result PolicyDefinition, ae error) { +func (client PolicyDefinitionsClient) Get(policyDefinitionName string) (result PolicyDefinition, err error) { req, err := client.GetPreparer(policyDefinitionName) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/PolicyDefinitionsClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.PolicyDefinitionsClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/PolicyDefinitionsClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.PolicyDefinitionsClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/PolicyDefinitionsClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.PolicyDefinitionsClient", "Get", resp, "Failure responding to request") } return @@ -213,7 +214,7 @@ func (client PolicyDefinitionsClient) GetPreparer(policyDefinitionName string) ( // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client PolicyDefinitionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -222,7 +223,7 @@ func (client PolicyDefinitionsClient) GetResponder(resp *http.Response) (result err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/provideroperationdetails.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/provideroperationdetails.go index ecf62fd2ac2f..8b6f05a1f335 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/provideroperationdetails.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/provideroperationdetails.go @@ -14,12 +14,13 @@ package resources // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -45,21 +46,21 @@ func NewProviderOperationDetailsClientWithBaseURI(baseURI string, subscriptionID // List gets a list of resource providers. // // resourceProviderNamespace is resource identity. -func (client ProviderOperationDetailsClient) List(resourceProviderNamespace string, apiVersion string) (result ResourceProviderOperationDetailListResult, ae error) { +func (client ProviderOperationDetailsClient) List(resourceProviderNamespace string, apiVersion string) (result ResourceProviderOperationDetailListResult, err error) { req, err := client.ListPreparer(resourceProviderNamespace, apiVersion) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/ProviderOperationDetailsClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.ProviderOperationDetailsClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/ProviderOperationDetailsClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.ProviderOperationDetailsClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/ProviderOperationDetailsClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.ProviderOperationDetailsClient", "List", resp, "Failure responding to request") } return @@ -88,7 +89,7 @@ func (client ProviderOperationDetailsClient) ListPreparer(resourceProviderNamesp // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client ProviderOperationDetailsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusNoContent) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -97,7 +98,7 @@ func (client ProviderOperationDetailsClient) ListResponder(resp *http.Response) err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -105,10 +106,10 @@ func (client ProviderOperationDetailsClient) ListResponder(resp *http.Response) } // ListNextResults retrieves the next set of results, if any. -func (client ProviderOperationDetailsClient) ListNextResults(lastResults ResourceProviderOperationDetailListResult) (result ResourceProviderOperationDetailListResult, ae error) { +func (client ProviderOperationDetailsClient) ListNextResults(lastResults ResourceProviderOperationDetailListResult) (result ResourceProviderOperationDetailListResult, err error) { req, err := lastResults.ResourceProviderOperationDetailListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "resources/ProviderOperationDetailsClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "resources.ProviderOperationDetailsClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -117,12 +118,12 @@ func (client ProviderOperationDetailsClient) ListNextResults(lastResults Resourc resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/ProviderOperationDetailsClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "resources.ProviderOperationDetailsClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/ProviderOperationDetailsClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "resources.ProviderOperationDetailsClient", "List", resp, "Failure responding to next results request request") } return diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/providers.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/providers.go index 2d030fc5ab17..0e870919aa8e 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/providers.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/providers.go @@ -14,12 +14,13 @@ package resources // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -44,21 +45,21 @@ func NewProvidersClientWithBaseURI(baseURI string, subscriptionID string) Provid // Get gets a resource provider. // // resourceProviderNamespace is namespace of the resource provider. -func (client ProvidersClient) Get(resourceProviderNamespace string) (result Provider, ae error) { +func (client ProvidersClient) Get(resourceProviderNamespace string) (result Provider, err error) { req, err := client.GetPreparer(resourceProviderNamespace) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/ProvidersClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.ProvidersClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/ProvidersClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.ProvidersClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/ProvidersClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.ProvidersClient", "Get", resp, "Failure responding to request") } return @@ -87,7 +88,7 @@ func (client ProvidersClient) GetPreparer(resourceProviderNamespace string) (*ht // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client ProvidersClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -96,7 +97,7 @@ func (client ProvidersClient) GetResponder(resp *http.Response) (result Provider err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -106,28 +107,28 @@ func (client ProvidersClient) GetResponder(resp *http.Response) (result Provider // List gets a list of resource providers. // // top is query parameters. If null is passed returns all deployments. -func (client ProvidersClient) List(top *int) (result ProviderListResult, ae error) { +func (client ProvidersClient) List(top *int32) (result ProviderListResult, err error) { req, err := client.ListPreparer(top) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/ProvidersClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.ProvidersClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/ProvidersClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.ProvidersClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/ProvidersClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.ProvidersClient", "List", resp, "Failure responding to request") } return } // ListPreparer prepares the List request. -func (client ProvidersClient) ListPreparer(top *int) (*http.Request, error) { +func (client ProvidersClient) ListPreparer(top *int32) (*http.Request, error) { pathParameters := map[string]interface{}{ "subscriptionId": url.QueryEscape(client.SubscriptionID), } @@ -151,7 +152,7 @@ func (client ProvidersClient) ListPreparer(top *int) (*http.Request, error) { // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client ProvidersClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -160,7 +161,7 @@ func (client ProvidersClient) ListResponder(resp *http.Response) (result Provide err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -168,10 +169,10 @@ func (client ProvidersClient) ListResponder(resp *http.Response) (result Provide } // ListNextResults retrieves the next set of results, if any. -func (client ProvidersClient) ListNextResults(lastResults ProviderListResult) (result ProviderListResult, ae error) { +func (client ProvidersClient) ListNextResults(lastResults ProviderListResult) (result ProviderListResult, err error) { req, err := lastResults.ProviderListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "resources/ProvidersClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "resources.ProvidersClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -180,12 +181,12 @@ func (client ProvidersClient) ListNextResults(lastResults ProviderListResult) (r resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/ProvidersClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "resources.ProvidersClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/ProvidersClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "resources.ProvidersClient", "List", resp, "Failure responding to next results request request") } return @@ -194,21 +195,21 @@ func (client ProvidersClient) ListNextResults(lastResults ProviderListResult) (r // Register registers provider to be used with a subscription. // // resourceProviderNamespace is namespace of the resource provider. -func (client ProvidersClient) Register(resourceProviderNamespace string) (result Provider, ae error) { +func (client ProvidersClient) Register(resourceProviderNamespace string) (result Provider, err error) { req, err := client.RegisterPreparer(resourceProviderNamespace) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/ProvidersClient", "Register", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.ProvidersClient", "Register", nil, "Failure preparing request") } resp, err := client.RegisterSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/ProvidersClient", "Register", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.ProvidersClient", "Register", resp, "Failure sending request") } result, err = client.RegisterResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/ProvidersClient", "Register", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.ProvidersClient", "Register", resp, "Failure responding to request") } return @@ -237,7 +238,7 @@ func (client ProvidersClient) RegisterPreparer(resourceProviderNamespace string) // RegisterSender sends the Register request. The method will close the // http.Response Body if it receives an error. func (client ProvidersClient) RegisterSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // RegisterResponder handles the response to the Register request. The method always @@ -246,7 +247,7 @@ func (client ProvidersClient) RegisterResponder(resp *http.Response) (result Pro err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -256,21 +257,21 @@ func (client ProvidersClient) RegisterResponder(resp *http.Response) (result Pro // Unregister unregisters provider from a subscription. // // resourceProviderNamespace is namespace of the resource provider. -func (client ProvidersClient) Unregister(resourceProviderNamespace string) (result Provider, ae error) { +func (client ProvidersClient) Unregister(resourceProviderNamespace string) (result Provider, err error) { req, err := client.UnregisterPreparer(resourceProviderNamespace) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/ProvidersClient", "Unregister", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.ProvidersClient", "Unregister", nil, "Failure preparing request") } resp, err := client.UnregisterSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/ProvidersClient", "Unregister", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.ProvidersClient", "Unregister", resp, "Failure sending request") } result, err = client.UnregisterResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/ProvidersClient", "Unregister", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.ProvidersClient", "Unregister", resp, "Failure responding to request") } return @@ -299,7 +300,7 @@ func (client ProvidersClient) UnregisterPreparer(resourceProviderNamespace strin // UnregisterSender sends the Unregister request. The method will close the // http.Response Body if it receives an error. func (client ProvidersClient) UnregisterSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // UnregisterResponder handles the response to the Unregister request. The method always @@ -308,7 +309,7 @@ func (client ProvidersClient) UnregisterResponder(resp *http.Response) (result P err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/resources.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/resources.go index dcdc32bf056d..3a1e2c0197c3 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/resources.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/resources.go @@ -14,12 +14,13 @@ package resources // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -45,21 +46,21 @@ func NewClientWithBaseURI(baseURI string, subscriptionID string) Client { // insensitive. resourceProviderNamespace is resource identity. // parentResourcePath is resource identity. resourceType is resource // identity. resourceName is resource identity. -func (client Client) CheckExistence(resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, apiVersion string) (result autorest.Response, ae error) { +func (client Client) CheckExistence(resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, apiVersion string) (result autorest.Response, err error) { req, err := client.CheckExistencePreparer(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/Client", "CheckExistence", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.Client", "CheckExistence", nil, "Failure preparing request") } resp, err := client.CheckExistenceSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "resources/Client", "CheckExistence", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.Client", "CheckExistence", resp, "Failure sending request") } result, err = client.CheckExistenceResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/Client", "CheckExistence", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.Client", "CheckExistence", resp, "Failure responding to request") } return @@ -92,7 +93,7 @@ func (client Client) CheckExistencePreparer(resourceGroupName string, resourcePr // CheckExistenceSender sends the CheckExistence request. The method will close the // http.Response Body if it receives an error. func (client Client) CheckExistenceSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusNoContent, http.StatusNotFound) + return autorest.SendWithSender(client, req) } // CheckExistenceResponder handles the response to the CheckExistence request. The method always @@ -101,7 +102,7 @@ func (client Client) CheckExistenceResponder(resp *http.Response) (result autore err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent, http.StatusNotFound), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent, http.StatusNotFound), autorest.ByClosing()) result.Response = resp return @@ -114,21 +115,21 @@ func (client Client) CheckExistenceResponder(resp *http.Response) (result autore // parentResourcePath is resource identity. resourceType is resource // identity. resourceName is resource identity. parameters is create or // update resource parameters. -func (client Client) CreateOrUpdate(resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, apiVersion string, parameters GenericResource) (result GenericResource, ae error) { +func (client Client) CreateOrUpdate(resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, apiVersion string, parameters GenericResource) (result GenericResource, err error) { req, err := client.CreateOrUpdatePreparer(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion, parameters) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/Client", "CreateOrUpdate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.Client", "CreateOrUpdate", nil, "Failure preparing request") } resp, err := client.CreateOrUpdateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/Client", "CreateOrUpdate", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.Client", "CreateOrUpdate", resp, "Failure sending request") } result, err = client.CreateOrUpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/Client", "CreateOrUpdate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.Client", "CreateOrUpdate", resp, "Failure responding to request") } return @@ -162,7 +163,7 @@ func (client Client) CreateOrUpdatePreparer(resourceGroupName string, resourcePr // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client Client) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusCreated, http.StatusOK) + return autorest.SendWithSender(client, req) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always @@ -171,7 +172,7 @@ func (client Client) CreateOrUpdateResponder(resp *http.Response) (result Generi err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -184,21 +185,21 @@ func (client Client) CreateOrUpdateResponder(resp *http.Response) (result Generi // insensitive. resourceProviderNamespace is resource identity. // parentResourcePath is resource identity. resourceType is resource // identity. resourceName is resource identity. -func (client Client) Delete(resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, apiVersion string) (result autorest.Response, ae error) { +func (client Client) Delete(resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, apiVersion string) (result autorest.Response, err error) { req, err := client.DeletePreparer(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/Client", "Delete", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.Client", "Delete", nil, "Failure preparing request") } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "resources/Client", "Delete", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.Client", "Delete", resp, "Failure sending request") } result, err = client.DeleteResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/Client", "Delete", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.Client", "Delete", resp, "Failure responding to request") } return @@ -231,7 +232,7 @@ func (client Client) DeletePreparer(resourceGroupName string, resourceProviderNa // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client Client) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusNoContent, http.StatusAccepted) + return autorest.SendWithSender(client, req) } // DeleteResponder handles the response to the Delete request. The method always @@ -240,7 +241,7 @@ func (client Client) DeleteResponder(resp *http.Response) (result autorest.Respo err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent, http.StatusAccepted), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return @@ -252,21 +253,21 @@ func (client Client) DeleteResponder(resp *http.Response) (result autorest.Respo // insensitive. resourceProviderNamespace is resource identity. // parentResourcePath is resource identity. resourceType is resource // identity. resourceName is resource identity. -func (client Client) Get(resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, apiVersion string) (result GenericResource, ae error) { +func (client Client) Get(resourceGroupName string, resourceProviderNamespace string, parentResourcePath string, resourceType string, resourceName string, apiVersion string) (result GenericResource, err error) { req, err := client.GetPreparer(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/Client", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.Client", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/Client", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.Client", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/Client", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.Client", "Get", resp, "Failure responding to request") } return @@ -299,7 +300,7 @@ func (client Client) GetPreparer(resourceGroupName string, resourceProviderNames // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client Client) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusNoContent) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -308,7 +309,7 @@ func (client Client) GetResponder(resp *http.Response) (result GenericResource, err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -319,28 +320,28 @@ func (client Client) GetResponder(resp *http.Response) (result GenericResource, // // filter is the filter to apply on the operation. top is query parameters. If // null is passed returns all resource groups. -func (client Client) List(filter string, top *int) (result ResourceListResult, ae error) { +func (client Client) List(filter string, top *int32) (result ResourceListResult, err error) { req, err := client.ListPreparer(filter, top) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/Client", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.Client", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/Client", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.Client", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/Client", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.Client", "List", resp, "Failure responding to request") } return } // ListPreparer prepares the List request. -func (client Client) ListPreparer(filter string, top *int) (*http.Request, error) { +func (client Client) ListPreparer(filter string, top *int32) (*http.Request, error) { pathParameters := map[string]interface{}{ "subscriptionId": url.QueryEscape(client.SubscriptionID), } @@ -367,7 +368,7 @@ func (client Client) ListPreparer(filter string, top *int) (*http.Request, error // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client Client) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -376,7 +377,7 @@ func (client Client) ListResponder(resp *http.Response) (result ResourceListResu err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -384,10 +385,10 @@ func (client Client) ListResponder(resp *http.Response) (result ResourceListResu } // ListNextResults retrieves the next set of results, if any. -func (client Client) ListNextResults(lastResults ResourceListResult) (result ResourceListResult, ae error) { +func (client Client) ListNextResults(lastResults ResourceListResult) (result ResourceListResult, err error) { req, err := lastResults.ResourceListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "resources/Client", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "resources.Client", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -396,44 +397,47 @@ func (client Client) ListNextResults(lastResults ResourceListResult) (result Res resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/Client", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "resources.Client", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/Client", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "resources.Client", "List", resp, "Failure responding to next results request request") } return } // MoveResources begin moving resources.To determine whether the operation has -// finished processing the request, call GetLongRunningOperationStatus. +// finished processing the request, call GetLongRunningOperationStatus. This +// method may poll for completion. Polling can be canceled by passing the +// cancel channel argument. The channel will be used to cancel polling and +// any outstanding HTTP requests. // // sourceResourceGroupName is source resource group name. parameters is move // resources' parameters. -func (client Client) MoveResources(sourceResourceGroupName string, parameters MoveInfo) (result autorest.Response, ae error) { - req, err := client.MoveResourcesPreparer(sourceResourceGroupName, parameters) +func (client Client) MoveResources(sourceResourceGroupName string, parameters MoveInfo, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.MoveResourcesPreparer(sourceResourceGroupName, parameters, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/Client", "MoveResources", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.Client", "MoveResources", nil, "Failure preparing request") } resp, err := client.MoveResourcesSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "resources/Client", "MoveResources", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.Client", "MoveResources", resp, "Failure sending request") } result, err = client.MoveResourcesResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/Client", "MoveResources", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.Client", "MoveResources", resp, "Failure responding to request") } return } // MoveResourcesPreparer prepares the MoveResources request. -func (client Client) MoveResourcesPreparer(sourceResourceGroupName string, parameters MoveInfo) (*http.Request, error) { +func (client Client) MoveResourcesPreparer(sourceResourceGroupName string, parameters MoveInfo, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "sourceResourceGroupName": url.QueryEscape(sourceResourceGroupName), "subscriptionId": url.QueryEscape(client.SubscriptionID), @@ -443,7 +447,7 @@ func (client Client) MoveResourcesPreparer(sourceResourceGroupName string, param "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), @@ -456,7 +460,9 @@ func (client Client) MoveResourcesPreparer(sourceResourceGroupName string, param // MoveResourcesSender sends the MoveResources request. The method will close the // http.Response Body if it receives an error. func (client Client) MoveResourcesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted, http.StatusNoContent) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // MoveResourcesResponder handles the response to the MoveResources request. The method always @@ -465,7 +471,7 @@ func (client Client) MoveResourcesResponder(resp *http.Response) (result autores err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/tags.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/tags.go index aec33be2c615..7e5992805cbc 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/tags.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/tags.go @@ -14,12 +14,13 @@ package resources // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -42,21 +43,21 @@ func NewTagsClientWithBaseURI(baseURI string, subscriptionID string) TagsClient // CreateOrUpdate create a subscription resource tag. // // tagName is the name of the tag. -func (client TagsClient) CreateOrUpdate(tagName string) (result TagDetails, ae error) { +func (client TagsClient) CreateOrUpdate(tagName string) (result TagDetails, err error) { req, err := client.CreateOrUpdatePreparer(tagName) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/TagsClient", "CreateOrUpdate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.TagsClient", "CreateOrUpdate", nil, "Failure preparing request") } resp, err := client.CreateOrUpdateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/TagsClient", "CreateOrUpdate", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.TagsClient", "CreateOrUpdate", resp, "Failure sending request") } result, err = client.CreateOrUpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/TagsClient", "CreateOrUpdate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.TagsClient", "CreateOrUpdate", resp, "Failure responding to request") } return @@ -85,7 +86,7 @@ func (client TagsClient) CreateOrUpdatePreparer(tagName string) (*http.Request, // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client TagsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusCreated) + return autorest.SendWithSender(client, req) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always @@ -94,7 +95,7 @@ func (client TagsClient) CreateOrUpdateResponder(resp *http.Response) (result Ta err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -104,21 +105,21 @@ func (client TagsClient) CreateOrUpdateResponder(resp *http.Response) (result Ta // CreateOrUpdateValue create a subscription resource tag value. // // tagName is the name of the tag. tagValue is the value of the tag. -func (client TagsClient) CreateOrUpdateValue(tagName string, tagValue string) (result TagValue, ae error) { +func (client TagsClient) CreateOrUpdateValue(tagName string, tagValue string) (result TagValue, err error) { req, err := client.CreateOrUpdateValuePreparer(tagName, tagValue) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/TagsClient", "CreateOrUpdateValue", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.TagsClient", "CreateOrUpdateValue", nil, "Failure preparing request") } resp, err := client.CreateOrUpdateValueSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/TagsClient", "CreateOrUpdateValue", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.TagsClient", "CreateOrUpdateValue", resp, "Failure sending request") } result, err = client.CreateOrUpdateValueResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/TagsClient", "CreateOrUpdateValue", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.TagsClient", "CreateOrUpdateValue", resp, "Failure responding to request") } return @@ -148,7 +149,7 @@ func (client TagsClient) CreateOrUpdateValuePreparer(tagName string, tagValue st // CreateOrUpdateValueSender sends the CreateOrUpdateValue request. The method will close the // http.Response Body if it receives an error. func (client TagsClient) CreateOrUpdateValueSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusCreated) + return autorest.SendWithSender(client, req) } // CreateOrUpdateValueResponder handles the response to the CreateOrUpdateValue request. The method always @@ -157,7 +158,7 @@ func (client TagsClient) CreateOrUpdateValueResponder(resp *http.Response) (resu err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -167,21 +168,21 @@ func (client TagsClient) CreateOrUpdateValueResponder(resp *http.Response) (resu // Delete delete a subscription resource tag. // // tagName is the name of the tag. -func (client TagsClient) Delete(tagName string) (result autorest.Response, ae error) { +func (client TagsClient) Delete(tagName string) (result autorest.Response, err error) { req, err := client.DeletePreparer(tagName) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/TagsClient", "Delete", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.TagsClient", "Delete", nil, "Failure preparing request") } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "resources/TagsClient", "Delete", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.TagsClient", "Delete", resp, "Failure sending request") } result, err = client.DeleteResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/TagsClient", "Delete", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.TagsClient", "Delete", resp, "Failure responding to request") } return @@ -210,7 +211,7 @@ func (client TagsClient) DeletePreparer(tagName string) (*http.Request, error) { // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client TagsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusNoContent) + return autorest.SendWithSender(client, req) } // DeleteResponder handles the response to the Delete request. The method always @@ -219,7 +220,7 @@ func (client TagsClient) DeleteResponder(resp *http.Response) (result autorest.R err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return @@ -228,21 +229,21 @@ func (client TagsClient) DeleteResponder(resp *http.Response) (result autorest.R // DeleteValue delete a subscription resource tag value. // // tagName is the name of the tag. tagValue is the value of the tag. -func (client TagsClient) DeleteValue(tagName string, tagValue string) (result autorest.Response, ae error) { +func (client TagsClient) DeleteValue(tagName string, tagValue string) (result autorest.Response, err error) { req, err := client.DeleteValuePreparer(tagName, tagValue) if err != nil { - return result, autorest.NewErrorWithError(err, "resources/TagsClient", "DeleteValue", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.TagsClient", "DeleteValue", nil, "Failure preparing request") } resp, err := client.DeleteValueSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "resources/TagsClient", "DeleteValue", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.TagsClient", "DeleteValue", resp, "Failure sending request") } result, err = client.DeleteValueResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/TagsClient", "DeleteValue", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.TagsClient", "DeleteValue", resp, "Failure responding to request") } return @@ -272,7 +273,7 @@ func (client TagsClient) DeleteValuePreparer(tagName string, tagValue string) (* // DeleteValueSender sends the DeleteValue request. The method will close the // http.Response Body if it receives an error. func (client TagsClient) DeleteValueSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusNoContent) + return autorest.SendWithSender(client, req) } // DeleteValueResponder handles the response to the DeleteValue request. The method always @@ -281,28 +282,28 @@ func (client TagsClient) DeleteValueResponder(resp *http.Response) (result autor err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return } // List get a list of subscription resource tags. -func (client TagsClient) List() (result TagsListResult, ae error) { +func (client TagsClient) List() (result TagsListResult, err error) { req, err := client.ListPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "resources/TagsClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "resources.TagsClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/TagsClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "resources.TagsClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/TagsClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "resources.TagsClient", "List", resp, "Failure responding to request") } return @@ -330,7 +331,7 @@ func (client TagsClient) ListPreparer() (*http.Request, error) { // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client TagsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -339,7 +340,7 @@ func (client TagsClient) ListResponder(resp *http.Response) (result TagsListResu err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -347,10 +348,10 @@ func (client TagsClient) ListResponder(resp *http.Response) (result TagsListResu } // ListNextResults retrieves the next set of results, if any. -func (client TagsClient) ListNextResults(lastResults TagsListResult) (result TagsListResult, ae error) { +func (client TagsClient) ListNextResults(lastResults TagsListResult) (result TagsListResult, err error) { req, err := lastResults.TagsListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "resources/TagsClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "resources.TagsClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -359,12 +360,12 @@ func (client TagsClient) ListNextResults(lastResults TagsListResult) (result Tag resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "resources/TagsClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "resources.TagsClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "resources/TagsClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "resources.TagsClient", "List", resp, "Failure responding to next results request request") } return diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/version.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/version.go index 695898636c25..9e7e9f1eae77 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/version.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/resources/resources/version.go @@ -14,7 +14,7 @@ package resources // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -23,18 +23,18 @@ import ( ) const ( - major = "0" - minor = "4" - patch = "0" + major = "2" + minor = "1" + patch = "1" // Always begin a "tag" with a dash (as per http://semver.org) tag = "-beta" semVerFormat = "%s.%s.%s%s" - userAgentFormat = "Azure-SDK-for-Go/%s;Package arm/%s;API %s" + userAgentFormat = "Azure-SDK-for-Go/%s arm-%s/%s" ) // UserAgent returns the UserAgent string to use when sending http.Requests. func UserAgent() string { - return fmt.Sprintf(userAgentFormat, Version(), "resources", "2014-04-01-preview") + return fmt.Sprintf(userAgentFormat, Version(), "resources", "2015-11-01") } // Version returns the semantic version (see http://semver.org) of the client. diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/scheduler/client.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/scheduler/client.go index e1095c7c10c5..4d8528b26c2c 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/scheduler/client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/scheduler/client.go @@ -1,3 +1,6 @@ +// Package scheduler implements the Azure ARM Scheduler service API version +// 2016-01-01. +// package scheduler // Copyright (c) Microsoft and contributors. All rights reserved. @@ -14,12 +17,12 @@ package scheduler // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" ) const ( diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/scheduler/jobcollections.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/scheduler/jobcollections.go index b25b64526fb8..7758fab5ec02 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/scheduler/jobcollections.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/scheduler/jobcollections.go @@ -14,12 +14,13 @@ package scheduler // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -47,21 +48,21 @@ func NewJobCollectionsClientWithBaseURI(baseURI string, subscriptionID string) J // // resourceGroupName is the resource group name. jobCollectionName is the job // collection name. jobCollection is the job collection definition. -func (client JobCollectionsClient) CreateOrUpdate(resourceGroupName string, jobCollectionName string, jobCollection JobCollectionDefinition) (result JobCollectionDefinition, ae error) { +func (client JobCollectionsClient) CreateOrUpdate(resourceGroupName string, jobCollectionName string, jobCollection JobCollectionDefinition) (result JobCollectionDefinition, err error) { req, err := client.CreateOrUpdatePreparer(resourceGroupName, jobCollectionName, jobCollection) if err != nil { - return result, autorest.NewErrorWithError(err, "scheduler/JobCollectionsClient", "CreateOrUpdate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "scheduler.JobCollectionsClient", "CreateOrUpdate", nil, "Failure preparing request") } resp, err := client.CreateOrUpdateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "scheduler/JobCollectionsClient", "CreateOrUpdate", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "scheduler.JobCollectionsClient", "CreateOrUpdate", resp, "Failure sending request") } result, err = client.CreateOrUpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "scheduler/JobCollectionsClient", "CreateOrUpdate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "scheduler.JobCollectionsClient", "CreateOrUpdate", resp, "Failure responding to request") } return @@ -92,7 +93,7 @@ func (client JobCollectionsClient) CreateOrUpdatePreparer(resourceGroupName stri // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client JobCollectionsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusCreated) + return autorest.SendWithSender(client, req) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always @@ -101,7 +102,7 @@ func (client JobCollectionsClient) CreateOrUpdateResponder(resp *http.Response) err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -112,21 +113,21 @@ func (client JobCollectionsClient) CreateOrUpdateResponder(resp *http.Response) // // resourceGroupName is the resource group name. jobCollectionName is the job // collection name. -func (client JobCollectionsClient) Delete(resourceGroupName string, jobCollectionName string) (result autorest.Response, ae error) { +func (client JobCollectionsClient) Delete(resourceGroupName string, jobCollectionName string) (result autorest.Response, err error) { req, err := client.DeletePreparer(resourceGroupName, jobCollectionName) if err != nil { - return result, autorest.NewErrorWithError(err, "scheduler/JobCollectionsClient", "Delete", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "scheduler.JobCollectionsClient", "Delete", nil, "Failure preparing request") } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "scheduler/JobCollectionsClient", "Delete", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "scheduler.JobCollectionsClient", "Delete", resp, "Failure sending request") } result, err = client.DeleteResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "scheduler/JobCollectionsClient", "Delete", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "scheduler.JobCollectionsClient", "Delete", resp, "Failure responding to request") } return @@ -156,7 +157,7 @@ func (client JobCollectionsClient) DeletePreparer(resourceGroupName string, jobC // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client JobCollectionsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // DeleteResponder handles the response to the Delete request. The method always @@ -165,7 +166,7 @@ func (client JobCollectionsClient) DeleteResponder(resp *http.Response) (result err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByClosing()) result.Response = resp return @@ -175,21 +176,21 @@ func (client JobCollectionsClient) DeleteResponder(resp *http.Response) (result // // resourceGroupName is the resource group name. jobCollectionName is the job // collection name. -func (client JobCollectionsClient) Disable(resourceGroupName string, jobCollectionName string) (result autorest.Response, ae error) { +func (client JobCollectionsClient) Disable(resourceGroupName string, jobCollectionName string) (result autorest.Response, err error) { req, err := client.DisablePreparer(resourceGroupName, jobCollectionName) if err != nil { - return result, autorest.NewErrorWithError(err, "scheduler/JobCollectionsClient", "Disable", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "scheduler.JobCollectionsClient", "Disable", nil, "Failure preparing request") } resp, err := client.DisableSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "scheduler/JobCollectionsClient", "Disable", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "scheduler.JobCollectionsClient", "Disable", resp, "Failure sending request") } result, err = client.DisableResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "scheduler/JobCollectionsClient", "Disable", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "scheduler.JobCollectionsClient", "Disable", resp, "Failure responding to request") } return @@ -219,7 +220,7 @@ func (client JobCollectionsClient) DisablePreparer(resourceGroupName string, job // DisableSender sends the Disable request. The method will close the // http.Response Body if it receives an error. func (client JobCollectionsClient) DisableSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // DisableResponder handles the response to the Disable request. The method always @@ -228,7 +229,7 @@ func (client JobCollectionsClient) DisableResponder(resp *http.Response) (result err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByClosing()) result.Response = resp return @@ -238,21 +239,21 @@ func (client JobCollectionsClient) DisableResponder(resp *http.Response) (result // // resourceGroupName is the resource group name. jobCollectionName is the job // collection name. -func (client JobCollectionsClient) Enable(resourceGroupName string, jobCollectionName string) (result autorest.Response, ae error) { +func (client JobCollectionsClient) Enable(resourceGroupName string, jobCollectionName string) (result autorest.Response, err error) { req, err := client.EnablePreparer(resourceGroupName, jobCollectionName) if err != nil { - return result, autorest.NewErrorWithError(err, "scheduler/JobCollectionsClient", "Enable", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "scheduler.JobCollectionsClient", "Enable", nil, "Failure preparing request") } resp, err := client.EnableSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "scheduler/JobCollectionsClient", "Enable", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "scheduler.JobCollectionsClient", "Enable", resp, "Failure sending request") } result, err = client.EnableResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "scheduler/JobCollectionsClient", "Enable", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "scheduler.JobCollectionsClient", "Enable", resp, "Failure responding to request") } return @@ -282,7 +283,7 @@ func (client JobCollectionsClient) EnablePreparer(resourceGroupName string, jobC // EnableSender sends the Enable request. The method will close the // http.Response Body if it receives an error. func (client JobCollectionsClient) EnableSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // EnableResponder handles the response to the Enable request. The method always @@ -291,7 +292,7 @@ func (client JobCollectionsClient) EnableResponder(resp *http.Response) (result err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByClosing()) result.Response = resp return @@ -301,21 +302,21 @@ func (client JobCollectionsClient) EnableResponder(resp *http.Response) (result // // resourceGroupName is the resource group name. jobCollectionName is the job // collection name. -func (client JobCollectionsClient) Get(resourceGroupName string, jobCollectionName string) (result JobCollectionDefinition, ae error) { +func (client JobCollectionsClient) Get(resourceGroupName string, jobCollectionName string) (result JobCollectionDefinition, err error) { req, err := client.GetPreparer(resourceGroupName, jobCollectionName) if err != nil { - return result, autorest.NewErrorWithError(err, "scheduler/JobCollectionsClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "scheduler.JobCollectionsClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "scheduler/JobCollectionsClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "scheduler.JobCollectionsClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "scheduler/JobCollectionsClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "scheduler.JobCollectionsClient", "Get", resp, "Failure responding to request") } return @@ -345,7 +346,7 @@ func (client JobCollectionsClient) GetPreparer(resourceGroupName string, jobColl // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client JobCollectionsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -354,7 +355,7 @@ func (client JobCollectionsClient) GetResponder(resp *http.Response) (result Job err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -364,21 +365,21 @@ func (client JobCollectionsClient) GetResponder(resp *http.Response) (result Job // ListByResourceGroup gets all job collections under specified resource group. // // resourceGroupName is the resource group name. -func (client JobCollectionsClient) ListByResourceGroup(resourceGroupName string) (result JobCollectionListResult, ae error) { +func (client JobCollectionsClient) ListByResourceGroup(resourceGroupName string) (result JobCollectionListResult, err error) { req, err := client.ListByResourceGroupPreparer(resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "scheduler/JobCollectionsClient", "ListByResourceGroup", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "scheduler.JobCollectionsClient", "ListByResourceGroup", nil, "Failure preparing request") } resp, err := client.ListByResourceGroupSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "scheduler/JobCollectionsClient", "ListByResourceGroup", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "scheduler.JobCollectionsClient", "ListByResourceGroup", resp, "Failure sending request") } result, err = client.ListByResourceGroupResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "scheduler/JobCollectionsClient", "ListByResourceGroup", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "scheduler.JobCollectionsClient", "ListByResourceGroup", resp, "Failure responding to request") } return @@ -407,7 +408,7 @@ func (client JobCollectionsClient) ListByResourceGroupPreparer(resourceGroupName // ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the // http.Response Body if it receives an error. func (client JobCollectionsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always @@ -416,7 +417,7 @@ func (client JobCollectionsClient) ListByResourceGroupResponder(resp *http.Respo err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -424,10 +425,10 @@ func (client JobCollectionsClient) ListByResourceGroupResponder(resp *http.Respo } // ListByResourceGroupNextResults retrieves the next set of results, if any. -func (client JobCollectionsClient) ListByResourceGroupNextResults(lastResults JobCollectionListResult) (result JobCollectionListResult, ae error) { +func (client JobCollectionsClient) ListByResourceGroupNextResults(lastResults JobCollectionListResult) (result JobCollectionListResult, err error) { req, err := lastResults.JobCollectionListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "scheduler/JobCollectionsClient", "ListByResourceGroup", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "scheduler.JobCollectionsClient", "ListByResourceGroup", nil, "Failure preparing next results request request") } if req == nil { return @@ -436,33 +437,33 @@ func (client JobCollectionsClient) ListByResourceGroupNextResults(lastResults Jo resp, err := client.ListByResourceGroupSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "scheduler/JobCollectionsClient", "ListByResourceGroup", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "scheduler.JobCollectionsClient", "ListByResourceGroup", resp, "Failure sending next results request request") } result, err = client.ListByResourceGroupResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "scheduler/JobCollectionsClient", "ListByResourceGroup", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "scheduler.JobCollectionsClient", "ListByResourceGroup", resp, "Failure responding to next results request request") } return } // ListBySubscription gets all job collections under specified subscription. -func (client JobCollectionsClient) ListBySubscription() (result JobCollectionListResult, ae error) { +func (client JobCollectionsClient) ListBySubscription() (result JobCollectionListResult, err error) { req, err := client.ListBySubscriptionPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "scheduler/JobCollectionsClient", "ListBySubscription", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "scheduler.JobCollectionsClient", "ListBySubscription", nil, "Failure preparing request") } resp, err := client.ListBySubscriptionSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "scheduler/JobCollectionsClient", "ListBySubscription", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "scheduler.JobCollectionsClient", "ListBySubscription", resp, "Failure sending request") } result, err = client.ListBySubscriptionResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "scheduler/JobCollectionsClient", "ListBySubscription", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "scheduler.JobCollectionsClient", "ListBySubscription", resp, "Failure responding to request") } return @@ -490,7 +491,7 @@ func (client JobCollectionsClient) ListBySubscriptionPreparer() (*http.Request, // ListBySubscriptionSender sends the ListBySubscription request. The method will close the // http.Response Body if it receives an error. func (client JobCollectionsClient) ListBySubscriptionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListBySubscriptionResponder handles the response to the ListBySubscription request. The method always @@ -499,7 +500,7 @@ func (client JobCollectionsClient) ListBySubscriptionResponder(resp *http.Respon err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -507,10 +508,10 @@ func (client JobCollectionsClient) ListBySubscriptionResponder(resp *http.Respon } // ListBySubscriptionNextResults retrieves the next set of results, if any. -func (client JobCollectionsClient) ListBySubscriptionNextResults(lastResults JobCollectionListResult) (result JobCollectionListResult, ae error) { +func (client JobCollectionsClient) ListBySubscriptionNextResults(lastResults JobCollectionListResult) (result JobCollectionListResult, err error) { req, err := lastResults.JobCollectionListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "scheduler/JobCollectionsClient", "ListBySubscription", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "scheduler.JobCollectionsClient", "ListBySubscription", nil, "Failure preparing next results request request") } if req == nil { return @@ -519,12 +520,12 @@ func (client JobCollectionsClient) ListBySubscriptionNextResults(lastResults Job resp, err := client.ListBySubscriptionSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "scheduler/JobCollectionsClient", "ListBySubscription", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "scheduler.JobCollectionsClient", "ListBySubscription", resp, "Failure sending next results request request") } result, err = client.ListBySubscriptionResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "scheduler/JobCollectionsClient", "ListBySubscription", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "scheduler.JobCollectionsClient", "ListBySubscription", resp, "Failure responding to next results request request") } return @@ -534,21 +535,21 @@ func (client JobCollectionsClient) ListBySubscriptionNextResults(lastResults Job // // resourceGroupName is the resource group name. jobCollectionName is the job // collection name. jobCollection is the job collection definition. -func (client JobCollectionsClient) Patch(resourceGroupName string, jobCollectionName string, jobCollection JobCollectionDefinition) (result JobCollectionDefinition, ae error) { +func (client JobCollectionsClient) Patch(resourceGroupName string, jobCollectionName string, jobCollection JobCollectionDefinition) (result JobCollectionDefinition, err error) { req, err := client.PatchPreparer(resourceGroupName, jobCollectionName, jobCollection) if err != nil { - return result, autorest.NewErrorWithError(err, "scheduler/JobCollectionsClient", "Patch", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "scheduler.JobCollectionsClient", "Patch", nil, "Failure preparing request") } resp, err := client.PatchSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "scheduler/JobCollectionsClient", "Patch", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "scheduler.JobCollectionsClient", "Patch", resp, "Failure sending request") } result, err = client.PatchResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "scheduler/JobCollectionsClient", "Patch", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "scheduler.JobCollectionsClient", "Patch", resp, "Failure responding to request") } return @@ -579,7 +580,7 @@ func (client JobCollectionsClient) PatchPreparer(resourceGroupName string, jobCo // PatchSender sends the Patch request. The method will close the // http.Response Body if it receives an error. func (client JobCollectionsClient) PatchSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // PatchResponder handles the response to the Patch request. The method always @@ -588,7 +589,7 @@ func (client JobCollectionsClient) PatchResponder(resp *http.Response) (result J err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/scheduler/jobs.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/scheduler/jobs.go index 9d27c6d20f35..5a0dd98a2cb5 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/scheduler/jobs.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/scheduler/jobs.go @@ -14,12 +14,13 @@ package scheduler // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -43,21 +44,21 @@ func NewJobsClientWithBaseURI(baseURI string, subscriptionID string) JobsClient // // resourceGroupName is the resource group name. jobCollectionName is the job // collection name. jobName is the job name. job is the job definition. -func (client JobsClient) CreateOrUpdate(resourceGroupName string, jobCollectionName string, jobName string, job JobDefinition) (result JobDefinition, ae error) { +func (client JobsClient) CreateOrUpdate(resourceGroupName string, jobCollectionName string, jobName string, job JobDefinition) (result JobDefinition, err error) { req, err := client.CreateOrUpdatePreparer(resourceGroupName, jobCollectionName, jobName, job) if err != nil { - return result, autorest.NewErrorWithError(err, "scheduler/JobsClient", "CreateOrUpdate", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "scheduler.JobsClient", "CreateOrUpdate", nil, "Failure preparing request") } resp, err := client.CreateOrUpdateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "scheduler/JobsClient", "CreateOrUpdate", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "scheduler.JobsClient", "CreateOrUpdate", resp, "Failure sending request") } result, err = client.CreateOrUpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "scheduler/JobsClient", "CreateOrUpdate", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "scheduler.JobsClient", "CreateOrUpdate", resp, "Failure responding to request") } return @@ -89,7 +90,7 @@ func (client JobsClient) CreateOrUpdatePreparer(resourceGroupName string, jobCol // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client JobsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusCreated) + return autorest.SendWithSender(client, req) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always @@ -98,7 +99,7 @@ func (client JobsClient) CreateOrUpdateResponder(resp *http.Response) (result Jo err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -109,21 +110,21 @@ func (client JobsClient) CreateOrUpdateResponder(resp *http.Response) (result Jo // // resourceGroupName is the resource group name. jobCollectionName is the job // collection name. jobName is the job name. -func (client JobsClient) Delete(resourceGroupName string, jobCollectionName string, jobName string) (result autorest.Response, ae error) { +func (client JobsClient) Delete(resourceGroupName string, jobCollectionName string, jobName string) (result autorest.Response, err error) { req, err := client.DeletePreparer(resourceGroupName, jobCollectionName, jobName) if err != nil { - return result, autorest.NewErrorWithError(err, "scheduler/JobsClient", "Delete", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "scheduler.JobsClient", "Delete", nil, "Failure preparing request") } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "scheduler/JobsClient", "Delete", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "scheduler.JobsClient", "Delete", resp, "Failure sending request") } result, err = client.DeleteResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "scheduler/JobsClient", "Delete", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "scheduler.JobsClient", "Delete", resp, "Failure responding to request") } return @@ -154,7 +155,7 @@ func (client JobsClient) DeletePreparer(resourceGroupName string, jobCollectionN // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client JobsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // DeleteResponder handles the response to the Delete request. The method always @@ -163,7 +164,7 @@ func (client JobsClient) DeleteResponder(resp *http.Response) (result autorest.R err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByClosing()) result.Response = resp return @@ -173,21 +174,21 @@ func (client JobsClient) DeleteResponder(resp *http.Response) (result autorest.R // // resourceGroupName is the resource group name. jobCollectionName is the job // collection name. jobName is the job name. -func (client JobsClient) Get(resourceGroupName string, jobCollectionName string, jobName string) (result JobDefinition, ae error) { +func (client JobsClient) Get(resourceGroupName string, jobCollectionName string, jobName string) (result JobDefinition, err error) { req, err := client.GetPreparer(resourceGroupName, jobCollectionName, jobName) if err != nil { - return result, autorest.NewErrorWithError(err, "scheduler/JobsClient", "Get", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "scheduler.JobsClient", "Get", nil, "Failure preparing request") } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "scheduler/JobsClient", "Get", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "scheduler.JobsClient", "Get", resp, "Failure sending request") } result, err = client.GetResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "scheduler/JobsClient", "Get", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "scheduler.JobsClient", "Get", resp, "Failure responding to request") } return @@ -218,7 +219,7 @@ func (client JobsClient) GetPreparer(resourceGroupName string, jobCollectionName // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client JobsClient) GetSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetResponder handles the response to the Get request. The method always @@ -227,7 +228,7 @@ func (client JobsClient) GetResponder(resp *http.Response) (result JobDefinition err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -241,28 +242,28 @@ func (client JobsClient) GetResponder(resp *http.Response) (result JobDefinition // [1..100]. skip is the (0-based) index of the job history list from which // to begin requesting entries. filter is the filter to apply on the job // state. -func (client JobsClient) List(resourceGroupName string, jobCollectionName string, top *int, skip *int, filter string) (result JobListResult, ae error) { +func (client JobsClient) List(resourceGroupName string, jobCollectionName string, top *int32, skip *int32, filter string) (result JobListResult, err error) { req, err := client.ListPreparer(resourceGroupName, jobCollectionName, top, skip, filter) if err != nil { - return result, autorest.NewErrorWithError(err, "scheduler/JobsClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "scheduler.JobsClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "scheduler/JobsClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "scheduler.JobsClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "scheduler/JobsClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "scheduler.JobsClient", "List", resp, "Failure responding to request") } return } // ListPreparer prepares the List request. -func (client JobsClient) ListPreparer(resourceGroupName string, jobCollectionName string, top *int, skip *int, filter string) (*http.Request, error) { +func (client JobsClient) ListPreparer(resourceGroupName string, jobCollectionName string, top *int32, skip *int32, filter string) (*http.Request, error) { pathParameters := map[string]interface{}{ "jobCollectionName": url.QueryEscape(jobCollectionName), "resourceGroupName": url.QueryEscape(resourceGroupName), @@ -294,7 +295,7 @@ func (client JobsClient) ListPreparer(resourceGroupName string, jobCollectionNam // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client JobsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -303,7 +304,7 @@ func (client JobsClient) ListResponder(resp *http.Response) (result JobListResul err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -311,10 +312,10 @@ func (client JobsClient) ListResponder(resp *http.Response) (result JobListResul } // ListNextResults retrieves the next set of results, if any. -func (client JobsClient) ListNextResults(lastResults JobListResult) (result JobListResult, ae error) { +func (client JobsClient) ListNextResults(lastResults JobListResult) (result JobListResult, err error) { req, err := lastResults.JobListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "scheduler/JobsClient", "List", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "scheduler.JobsClient", "List", nil, "Failure preparing next results request request") } if req == nil { return @@ -323,12 +324,12 @@ func (client JobsClient) ListNextResults(lastResults JobListResult) (result JobL resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "scheduler/JobsClient", "List", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "scheduler.JobsClient", "List", resp, "Failure sending next results request request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "scheduler/JobsClient", "List", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "scheduler.JobsClient", "List", resp, "Failure responding to next results request request") } return @@ -341,28 +342,28 @@ func (client JobsClient) ListNextResults(lastResults JobListResult) (result JobL // to request, in the of range [1..100]. skip is the (0-based) index of the // job history list from which to begin requesting entries. filter is the // filter to apply on the job state. -func (client JobsClient) ListJobHistory(resourceGroupName string, jobCollectionName string, jobName string, top *int, skip *int, filter string) (result JobHistoryListResult, ae error) { +func (client JobsClient) ListJobHistory(resourceGroupName string, jobCollectionName string, jobName string, top *int32, skip *int32, filter string) (result JobHistoryListResult, err error) { req, err := client.ListJobHistoryPreparer(resourceGroupName, jobCollectionName, jobName, top, skip, filter) if err != nil { - return result, autorest.NewErrorWithError(err, "scheduler/JobsClient", "ListJobHistory", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "scheduler.JobsClient", "ListJobHistory", nil, "Failure preparing request") } resp, err := client.ListJobHistorySender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "scheduler/JobsClient", "ListJobHistory", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "scheduler.JobsClient", "ListJobHistory", resp, "Failure sending request") } result, err = client.ListJobHistoryResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "scheduler/JobsClient", "ListJobHistory", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "scheduler.JobsClient", "ListJobHistory", resp, "Failure responding to request") } return } // ListJobHistoryPreparer prepares the ListJobHistory request. -func (client JobsClient) ListJobHistoryPreparer(resourceGroupName string, jobCollectionName string, jobName string, top *int, skip *int, filter string) (*http.Request, error) { +func (client JobsClient) ListJobHistoryPreparer(resourceGroupName string, jobCollectionName string, jobName string, top *int32, skip *int32, filter string) (*http.Request, error) { pathParameters := map[string]interface{}{ "jobCollectionName": url.QueryEscape(jobCollectionName), "jobName": url.QueryEscape(jobName), @@ -395,7 +396,7 @@ func (client JobsClient) ListJobHistoryPreparer(resourceGroupName string, jobCol // ListJobHistorySender sends the ListJobHistory request. The method will close the // http.Response Body if it receives an error. func (client JobsClient) ListJobHistorySender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListJobHistoryResponder handles the response to the ListJobHistory request. The method always @@ -404,7 +405,7 @@ func (client JobsClient) ListJobHistoryResponder(resp *http.Response) (result Jo err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -412,10 +413,10 @@ func (client JobsClient) ListJobHistoryResponder(resp *http.Response) (result Jo } // ListJobHistoryNextResults retrieves the next set of results, if any. -func (client JobsClient) ListJobHistoryNextResults(lastResults JobHistoryListResult) (result JobHistoryListResult, ae error) { +func (client JobsClient) ListJobHistoryNextResults(lastResults JobHistoryListResult) (result JobHistoryListResult, err error) { req, err := lastResults.JobHistoryListResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "scheduler/JobsClient", "ListJobHistory", autorest.UndefinedStatusCode, "Failure preparing next results request request") + return result, autorest.NewErrorWithError(err, "scheduler.JobsClient", "ListJobHistory", nil, "Failure preparing next results request request") } if req == nil { return @@ -424,12 +425,12 @@ func (client JobsClient) ListJobHistoryNextResults(lastResults JobHistoryListRes resp, err := client.ListJobHistorySender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "scheduler/JobsClient", "ListJobHistory", resp.StatusCode, "Failure sending next results request request") + return result, autorest.NewErrorWithError(err, "scheduler.JobsClient", "ListJobHistory", resp, "Failure sending next results request request") } result, err = client.ListJobHistoryResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "scheduler/JobsClient", "ListJobHistory", resp.StatusCode, "Failure responding to next results request request") + err = autorest.NewErrorWithError(err, "scheduler.JobsClient", "ListJobHistory", resp, "Failure responding to next results request request") } return @@ -439,21 +440,21 @@ func (client JobsClient) ListJobHistoryNextResults(lastResults JobHistoryListRes // // resourceGroupName is the resource group name. jobCollectionName is the job // collection name. jobName is the job name. job is the job definition. -func (client JobsClient) Patch(resourceGroupName string, jobCollectionName string, jobName string, job JobDefinition) (result JobDefinition, ae error) { +func (client JobsClient) Patch(resourceGroupName string, jobCollectionName string, jobName string, job JobDefinition) (result JobDefinition, err error) { req, err := client.PatchPreparer(resourceGroupName, jobCollectionName, jobName, job) if err != nil { - return result, autorest.NewErrorWithError(err, "scheduler/JobsClient", "Patch", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "scheduler.JobsClient", "Patch", nil, "Failure preparing request") } resp, err := client.PatchSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "scheduler/JobsClient", "Patch", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "scheduler.JobsClient", "Patch", resp, "Failure sending request") } result, err = client.PatchResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "scheduler/JobsClient", "Patch", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "scheduler.JobsClient", "Patch", resp, "Failure responding to request") } return @@ -485,7 +486,7 @@ func (client JobsClient) PatchPreparer(resourceGroupName string, jobCollectionNa // PatchSender sends the Patch request. The method will close the // http.Response Body if it receives an error. func (client JobsClient) PatchSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // PatchResponder handles the response to the Patch request. The method always @@ -494,7 +495,7 @@ func (client JobsClient) PatchResponder(resp *http.Response) (result JobDefiniti err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -505,21 +506,21 @@ func (client JobsClient) PatchResponder(resp *http.Response) (result JobDefiniti // // resourceGroupName is the resource group name. jobCollectionName is the job // collection name. jobName is the job name. -func (client JobsClient) Run(resourceGroupName string, jobCollectionName string, jobName string) (result autorest.Response, ae error) { +func (client JobsClient) Run(resourceGroupName string, jobCollectionName string, jobName string) (result autorest.Response, err error) { req, err := client.RunPreparer(resourceGroupName, jobCollectionName, jobName) if err != nil { - return result, autorest.NewErrorWithError(err, "scheduler/JobsClient", "Run", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "scheduler.JobsClient", "Run", nil, "Failure preparing request") } resp, err := client.RunSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "scheduler/JobsClient", "Run", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "scheduler.JobsClient", "Run", resp, "Failure sending request") } result, err = client.RunResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "scheduler/JobsClient", "Run", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "scheduler.JobsClient", "Run", resp, "Failure responding to request") } return @@ -550,7 +551,7 @@ func (client JobsClient) RunPreparer(resourceGroupName string, jobCollectionName // RunSender sends the Run request. The method will close the // http.Response Body if it receives an error. func (client JobsClient) RunSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // RunResponder handles the response to the Run request. The method always @@ -559,7 +560,7 @@ func (client JobsClient) RunResponder(resp *http.Response) (result autorest.Resp err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByClosing()) result.Response = resp return diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/scheduler/models.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/scheduler/models.go index 37ea1bd32e0c..e9f43dffd12a 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/scheduler/models.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/scheduler/models.go @@ -14,14 +14,14 @@ package scheduler // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/date" - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/to" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/date" + "github.com/Azure/go-autorest/autorest/to" "net/http" ) @@ -308,8 +308,8 @@ type JobCollectionProperties struct { // JobCollectionQuota is type JobCollectionQuota struct { - MaxJobCount *int `json:"maxJobCount,omitempty"` - MaxJobOccurrence *int `json:"maxJobOccurrence,omitempty"` + MaxJobCount *int32 `json:"maxJobCount,omitempty"` + MaxJobOccurrence *int32 `json:"maxJobOccurrence,omitempty"` MaxRecurrence *JobMaxRecurrence `json:"maxRecurrence,omitempty"` } @@ -348,8 +348,8 @@ type JobHistoryDefinitionProperties struct { ActionName JobHistoryActionName `json:"actionName,omitempty"` Status JobExecutionStatus `json:"status,omitempty"` Message *string `json:"message,omitempty"` - RetryCount *int `json:"retryCount,omitempty"` - RepeatCount *int `json:"repeatCount,omitempty"` + RetryCount *int32 `json:"retryCount,omitempty"` + RepeatCount *int32 `json:"repeatCount,omitempty"` } // JobHistoryFilter is @@ -398,7 +398,7 @@ func (client JobListResult) JobListResultPreparer() (*http.Request, error) { // JobMaxRecurrence is type JobMaxRecurrence struct { Frequency RecurrenceFrequency `json:"frequency,omitempty"` - Interval *int `json:"interval,omitempty"` + Interval *int32 `json:"interval,omitempty"` } // JobProperties is @@ -413,8 +413,8 @@ type JobProperties struct { // JobRecurrence is type JobRecurrence struct { Frequency RecurrenceFrequency `json:"frequency,omitempty"` - Interval *int `json:"interval,omitempty"` - Count *int `json:"count,omitempty"` + Interval *int32 `json:"interval,omitempty"` + Count *int32 `json:"count,omitempty"` EndTime *date.Time `json:"endTime,omitempty"` Schedule *JobRecurrenceSchedule `json:"schedule,omitempty"` } @@ -422,16 +422,16 @@ type JobRecurrence struct { // JobRecurrenceSchedule is type JobRecurrenceSchedule struct { WeekDays *[]DayOfWeek `json:"weekDays,omitempty"` - Hours *[]int `json:"hours,omitempty"` - Minutes *[]int `json:"minutes,omitempty"` - MonthDays *[]int `json:"monthDays,omitempty"` + Hours *[]int32 `json:"hours,omitempty"` + Minutes *[]int32 `json:"minutes,omitempty"` + MonthDays *[]int32 `json:"monthDays,omitempty"` MonthlyOccurrences *[]JobRecurrenceScheduleMonthlyOccurrence `json:"monthlyOccurrences,omitempty"` } // JobRecurrenceScheduleMonthlyOccurrence is type JobRecurrenceScheduleMonthlyOccurrence struct { Day JobScheduleDay `json:"day,omitempty"` - Occurrence *int `json:"Occurrence,omitempty"` + Occurrence *int32 `json:"Occurrence,omitempty"` } // JobStateFilter is @@ -441,9 +441,9 @@ type JobStateFilter struct { // JobStatus is type JobStatus struct { - ExecutionCount *int `json:"executionCount,omitempty"` - FailureCount *int `json:"failureCount,omitempty"` - FaultedCount *int `json:"faultedCount,omitempty"` + ExecutionCount *int32 `json:"executionCount,omitempty"` + FailureCount *int32 `json:"failureCount,omitempty"` + FaultedCount *int32 `json:"faultedCount,omitempty"` LastExecutionTime *date.Time `json:"lastExecutionTime,omitempty"` NextExecutionTime *date.Time `json:"nextExecutionTime,omitempty"` } @@ -461,7 +461,7 @@ type OAuthAuthentication struct { type RetryPolicy struct { RetryType RetryType `json:"retryType,omitempty"` RetryInterval *string `json:"retryInterval,omitempty"` - RetryCount *int `json:"retryCount,omitempty"` + RetryCount *int32 `json:"retryCount,omitempty"` } // ServiceBusAuthentication is diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/scheduler/version.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/scheduler/version.go index ff0772f514b4..8e2458f86c82 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/scheduler/version.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/scheduler/version.go @@ -14,7 +14,7 @@ package scheduler // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -23,13 +23,13 @@ import ( ) const ( - major = "0" - minor = "4" - patch = "0" + major = "2" + minor = "1" + patch = "1" // Always begin a "tag" with a dash (as per http://semver.org) tag = "-beta" semVerFormat = "%s.%s.%s%s" - userAgentFormat = "Azure-SDK-for-Go/%s;Package arm/%s;API %s" + userAgentFormat = "Azure-SDK-for-Go/%s arm-%s/%s" ) // UserAgent returns the UserAgent string to use when sending http.Requests. diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/storage/accounts.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/storage/accounts.go index 38315a84074a..4aef6a56b793 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/storage/accounts.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/storage/accounts.go @@ -14,12 +14,13 @@ package storage // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -45,21 +46,21 @@ func NewAccountsClientWithBaseURI(baseURI string, subscriptionID string) Account // accountName is the name of the storage account within the specified // resource group. Storage account names must be between 3 and 24 characters // in length and use numbers and lower-case letters only. -func (client AccountsClient) CheckNameAvailability(accountName AccountCheckNameAvailabilityParameters) (result CheckNameAvailabilityResult, ae error) { +func (client AccountsClient) CheckNameAvailability(accountName AccountCheckNameAvailabilityParameters) (result CheckNameAvailabilityResult, err error) { req, err := client.CheckNameAvailabilityPreparer(accountName) if err != nil { - return result, autorest.NewErrorWithError(err, "storage/AccountsClient", "CheckNameAvailability", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "CheckNameAvailability", nil, "Failure preparing request") } resp, err := client.CheckNameAvailabilitySender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "storage/AccountsClient", "CheckNameAvailability", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "CheckNameAvailability", resp, "Failure sending request") } result, err = client.CheckNameAvailabilityResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "storage/AccountsClient", "CheckNameAvailability", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "CheckNameAvailability", resp, "Failure responding to request") } return @@ -88,7 +89,7 @@ func (client AccountsClient) CheckNameAvailabilityPreparer(accountName AccountCh // CheckNameAvailabilitySender sends the CheckNameAvailability request. The method will close the // http.Response Body if it receives an error. func (client AccountsClient) CheckNameAvailabilitySender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // CheckNameAvailabilityResponder handles the response to the CheckNameAvailability request. The method always @@ -97,7 +98,7 @@ func (client AccountsClient) CheckNameAvailabilityResponder(resp *http.Response) err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -108,35 +109,38 @@ func (client AccountsClient) CheckNameAvailabilityResponder(resp *http.Response) // parameters. Existing accounts cannot be updated with this API and should // instead use the Update Storage Account API. If an account is already // created and subsequent PUT request is issued with exact same set of -// properties, then HTTP 200 would be returned. +// properties, then HTTP 200 would be returned. This method may poll for +// completion. Polling can be canceled by passing the cancel channel +// argument. The channel will be used to cancel polling and any outstanding +// HTTP requests. // // resourceGroupName is the name of the resource group within the user's // subscription. accountName is the name of the storage account within the // specified resource group. Storage account names must be between 3 and 24 // characters in length and use numbers and lower-case letters only. // parameters is the parameters to provide for the created account. -func (client AccountsClient) Create(resourceGroupName string, accountName string, parameters AccountCreateParameters) (result Account, ae error) { - req, err := client.CreatePreparer(resourceGroupName, accountName, parameters) +func (client AccountsClient) Create(resourceGroupName string, accountName string, parameters AccountCreateParameters, cancel <-chan struct{}) (result autorest.Response, err error) { + req, err := client.CreatePreparer(resourceGroupName, accountName, parameters, cancel) if err != nil { - return result, autorest.NewErrorWithError(err, "storage/AccountsClient", "Create", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "Create", nil, "Failure preparing request") } resp, err := client.CreateSender(req) if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "storage/AccountsClient", "Create", resp.StatusCode, "Failure sending request") + result.Response = resp + return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "Create", resp, "Failure sending request") } result, err = client.CreateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "storage/AccountsClient", "Create", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "Create", resp, "Failure responding to request") } return } // CreatePreparer prepares the Create request. -func (client AccountsClient) CreatePreparer(resourceGroupName string, accountName string, parameters AccountCreateParameters) (*http.Request, error) { +func (client AccountsClient) CreatePreparer(resourceGroupName string, accountName string, parameters AccountCreateParameters, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "accountName": url.QueryEscape(accountName), "resourceGroupName": url.QueryEscape(resourceGroupName), @@ -147,7 +151,7 @@ func (client AccountsClient) CreatePreparer(resourceGroupName string, accountNam "api-version": APIVersion, } - return autorest.Prepare(&http.Request{}, + return autorest.Prepare(&http.Request{Cancel: cancel}, autorest.AsJSON(), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), @@ -160,19 +164,20 @@ func (client AccountsClient) CreatePreparer(resourceGroupName string, accountNam // CreateSender sends the Create request. The method will close the // http.Response Body if it receives an error. func (client AccountsClient) CreateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusAccepted) + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } // CreateResponder handles the response to the Create request. The method always // closes the http.Response Body. -func (client AccountsClient) CreateResponder(resp *http.Response) (result Account, err error) { +func (client AccountsClient) CreateResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + result.Response = resp return } @@ -182,21 +187,21 @@ func (client AccountsClient) CreateResponder(resp *http.Response) (result Accoun // subscription. accountName is the name of the storage account within the // specified resource group. Storage account names must be between 3 and 24 // characters in length and use numbers and lower-case letters only. -func (client AccountsClient) Delete(resourceGroupName string, accountName string) (result autorest.Response, ae error) { +func (client AccountsClient) Delete(resourceGroupName string, accountName string) (result autorest.Response, err error) { req, err := client.DeletePreparer(resourceGroupName, accountName) if err != nil { - return result, autorest.NewErrorWithError(err, "storage/AccountsClient", "Delete", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "Delete", nil, "Failure preparing request") } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "storage/AccountsClient", "Delete", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "Delete", resp, "Failure sending request") } result, err = client.DeleteResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "storage/AccountsClient", "Delete", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "Delete", resp, "Failure responding to request") } return @@ -226,7 +231,7 @@ func (client AccountsClient) DeletePreparer(resourceGroupName string, accountNam // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client AccountsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK, http.StatusNoContent) + return autorest.SendWithSender(client, req) } // DeleteResponder handles the response to the Delete request. The method always @@ -235,7 +240,7 @@ func (client AccountsClient) DeleteResponder(resp *http.Response) (result autore err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return @@ -249,21 +254,21 @@ func (client AccountsClient) DeleteResponder(resp *http.Response) (result autore // subscription. accountName is the name of the storage account within the // specified resource group. Storage account names must be between 3 and 24 // characters in length and use numbers and lower-case letters only. -func (client AccountsClient) GetProperties(resourceGroupName string, accountName string) (result Account, ae error) { +func (client AccountsClient) GetProperties(resourceGroupName string, accountName string) (result Account, err error) { req, err := client.GetPropertiesPreparer(resourceGroupName, accountName) if err != nil { - return result, autorest.NewErrorWithError(err, "storage/AccountsClient", "GetProperties", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "GetProperties", nil, "Failure preparing request") } resp, err := client.GetPropertiesSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "storage/AccountsClient", "GetProperties", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "GetProperties", resp, "Failure sending request") } result, err = client.GetPropertiesResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "storage/AccountsClient", "GetProperties", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "GetProperties", resp, "Failure responding to request") } return @@ -293,7 +298,7 @@ func (client AccountsClient) GetPropertiesPreparer(resourceGroupName string, acc // GetPropertiesSender sends the GetProperties request. The method will close the // http.Response Body if it receives an error. func (client AccountsClient) GetPropertiesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // GetPropertiesResponder handles the response to the GetProperties request. The method always @@ -302,7 +307,7 @@ func (client AccountsClient) GetPropertiesResponder(resp *http.Response) (result err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -311,21 +316,21 @@ func (client AccountsClient) GetPropertiesResponder(resp *http.Response) (result // List lists all the storage accounts available under the subscription. Note // that storage keys are not returned; use the ListKeys operation for this. -func (client AccountsClient) List() (result AccountListResult, ae error) { +func (client AccountsClient) List() (result AccountListResult, err error) { req, err := client.ListPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "storage/AccountsClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "storage/AccountsClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "storage/AccountsClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "List", resp, "Failure responding to request") } return @@ -353,7 +358,7 @@ func (client AccountsClient) ListPreparer() (*http.Request, error) { // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client AccountsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -362,7 +367,7 @@ func (client AccountsClient) ListResponder(resp *http.Response) (result AccountL err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -375,21 +380,21 @@ func (client AccountsClient) ListResponder(resp *http.Response) (result AccountL // // resourceGroupName is the name of the resource group within the user's // subscription. -func (client AccountsClient) ListByResourceGroup(resourceGroupName string) (result AccountListResult, ae error) { +func (client AccountsClient) ListByResourceGroup(resourceGroupName string) (result AccountListResult, err error) { req, err := client.ListByResourceGroupPreparer(resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "storage/AccountsClient", "ListByResourceGroup", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "ListByResourceGroup", nil, "Failure preparing request") } resp, err := client.ListByResourceGroupSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "storage/AccountsClient", "ListByResourceGroup", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "ListByResourceGroup", resp, "Failure sending request") } result, err = client.ListByResourceGroupResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "storage/AccountsClient", "ListByResourceGroup", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "ListByResourceGroup", resp, "Failure responding to request") } return @@ -418,7 +423,7 @@ func (client AccountsClient) ListByResourceGroupPreparer(resourceGroupName strin // ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the // http.Response Body if it receives an error. func (client AccountsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always @@ -427,7 +432,7 @@ func (client AccountsClient) ListByResourceGroupResponder(resp *http.Response) ( err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -438,21 +443,21 @@ func (client AccountsClient) ListByResourceGroupResponder(resp *http.Response) ( // // resourceGroupName is the name of the resource group. accountName is the // name of the storage account. -func (client AccountsClient) ListKeys(resourceGroupName string, accountName string) (result AccountKeys, ae error) { +func (client AccountsClient) ListKeys(resourceGroupName string, accountName string) (result AccountKeys, err error) { req, err := client.ListKeysPreparer(resourceGroupName, accountName) if err != nil { - return result, autorest.NewErrorWithError(err, "storage/AccountsClient", "ListKeys", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "ListKeys", nil, "Failure preparing request") } resp, err := client.ListKeysSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "storage/AccountsClient", "ListKeys", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "ListKeys", resp, "Failure sending request") } result, err = client.ListKeysResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "storage/AccountsClient", "ListKeys", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "ListKeys", resp, "Failure responding to request") } return @@ -482,7 +487,7 @@ func (client AccountsClient) ListKeysPreparer(resourceGroupName string, accountN // ListKeysSender sends the ListKeys request. The method will close the // http.Response Body if it receives an error. func (client AccountsClient) ListKeysSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListKeysResponder handles the response to the ListKeys request. The method always @@ -491,7 +496,7 @@ func (client AccountsClient) ListKeysResponder(resp *http.Response) (result Acco err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -506,21 +511,21 @@ func (client AccountsClient) ListKeysResponder(resp *http.Response) (result Acco // characters in length and use numbers and lower-case letters only. // regenerateKey is specifies name of the key which should be regenerated. // key1 or key2 for the default keys -func (client AccountsClient) RegenerateKey(resourceGroupName string, accountName string, regenerateKey AccountRegenerateKeyParameters) (result AccountKeys, ae error) { +func (client AccountsClient) RegenerateKey(resourceGroupName string, accountName string, regenerateKey AccountRegenerateKeyParameters) (result AccountKeys, err error) { req, err := client.RegenerateKeyPreparer(resourceGroupName, accountName, regenerateKey) if err != nil { - return result, autorest.NewErrorWithError(err, "storage/AccountsClient", "RegenerateKey", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "RegenerateKey", nil, "Failure preparing request") } resp, err := client.RegenerateKeySender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "storage/AccountsClient", "RegenerateKey", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "RegenerateKey", resp, "Failure sending request") } result, err = client.RegenerateKeyResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "storage/AccountsClient", "RegenerateKey", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "RegenerateKey", resp, "Failure responding to request") } return @@ -551,7 +556,7 @@ func (client AccountsClient) RegenerateKeyPreparer(resourceGroupName string, acc // RegenerateKeySender sends the RegenerateKey request. The method will close the // http.Response Body if it receives an error. func (client AccountsClient) RegenerateKeySender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // RegenerateKeyResponder handles the response to the RegenerateKey request. The method always @@ -560,7 +565,7 @@ func (client AccountsClient) RegenerateKeyResponder(resp *http.Response) (result err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -586,21 +591,21 @@ func (client AccountsClient) RegenerateKeyResponder(resp *http.Response) (result // characters in length and use numbers and lower-case letters only. // parameters is the parameters to update on the account. Note that only one // property can be changed at a time using this API. -func (client AccountsClient) Update(resourceGroupName string, accountName string, parameters AccountUpdateParameters) (result Account, ae error) { +func (client AccountsClient) Update(resourceGroupName string, accountName string, parameters AccountUpdateParameters) (result Account, err error) { req, err := client.UpdatePreparer(resourceGroupName, accountName, parameters) if err != nil { - return result, autorest.NewErrorWithError(err, "storage/AccountsClient", "Update", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "Update", nil, "Failure preparing request") } resp, err := client.UpdateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "storage/AccountsClient", "Update", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "Update", resp, "Failure sending request") } result, err = client.UpdateResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "storage/AccountsClient", "Update", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "Update", resp, "Failure responding to request") } return @@ -631,7 +636,7 @@ func (client AccountsClient) UpdatePreparer(resourceGroupName string, accountNam // UpdateSender sends the Update request. The method will close the // http.Response Body if it receives an error. func (client AccountsClient) UpdateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // UpdateResponder handles the response to the Update request. The method always @@ -640,7 +645,7 @@ func (client AccountsClient) UpdateResponder(resp *http.Response) (result Accoun err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/storage/client.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/storage/client.go index c468e5d79f45..f1de4c266d94 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/storage/client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/storage/client.go @@ -1,3 +1,7 @@ +// Package storage implements the Azure ARM Storage service API version +// 2015-06-15. +// +// The Storage Management Client. package storage // Copyright (c) Microsoft and contributors. All rights reserved. @@ -14,12 +18,12 @@ package storage // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" ) const ( @@ -30,7 +34,7 @@ const ( DefaultBaseURI = "https://management.azure.com" ) -// ManagementClient is the the Storage Management Client. +// ManagementClient is the base client for Storage. type ManagementClient struct { autorest.Client BaseURI string diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/storage/models.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/storage/models.go index fca182c96022..2b15a0547f2c 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/storage/models.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/storage/models.go @@ -14,13 +14,13 @@ package storage // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/date" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/date" ) // AccountStatus enumerates the values for account status. @@ -199,8 +199,8 @@ type Resource struct { // Usage is describes Storage Resource Usage. type Usage struct { Unit UsageUnit `json:"unit,omitempty"` - CurrentValue *int `json:"currentValue,omitempty"` - Limit *int `json:"limit,omitempty"` + CurrentValue *int32 `json:"currentValue,omitempty"` + Limit *int32 `json:"limit,omitempty"` Name *UsageName `json:"name,omitempty"` } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/storage/usageoperations.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/storage/usageoperations.go index f99018a1b0f6..7b5bbe0b0929 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/storage/usageoperations.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/storage/usageoperations.go @@ -14,12 +14,13 @@ package storage // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "net/http" "net/url" ) @@ -43,21 +44,21 @@ func NewUsageOperationsClientWithBaseURI(baseURI string, subscriptionID string) // List gets the current usage count and the limit for the resources under the // subscription. -func (client UsageOperationsClient) List() (result UsageListResult, ae error) { +func (client UsageOperationsClient) List() (result UsageListResult, err error) { req, err := client.ListPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "storage/UsageOperationsClient", "List", autorest.UndefinedStatusCode, "Failure preparing request") + return result, autorest.NewErrorWithError(err, "storage.UsageOperationsClient", "List", nil, "Failure preparing request") } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "storage/UsageOperationsClient", "List", resp.StatusCode, "Failure sending request") + return result, autorest.NewErrorWithError(err, "storage.UsageOperationsClient", "List", resp, "Failure sending request") } result, err = client.ListResponder(resp) if err != nil { - ae = autorest.NewErrorWithError(err, "storage/UsageOperationsClient", "List", resp.StatusCode, "Failure responding to request") + err = autorest.NewErrorWithError(err, "storage.UsageOperationsClient", "List", resp, "Failure responding to request") } return @@ -85,7 +86,7 @@ func (client UsageOperationsClient) ListPreparer() (*http.Request, error) { // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client UsageOperationsClient) ListSender(req *http.Request) (*http.Response, error) { - return client.Send(req, http.StatusOK) + return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always @@ -94,7 +95,7 @@ func (client UsageOperationsClient) ListResponder(resp *http.Response) (result U err = autorest.Respond( resp, client.ByInspecting(), - autorest.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/storage/version.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/storage/version.go index 8d4883fa6b46..3432c57eecb3 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/storage/version.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/storage/version.go @@ -14,7 +14,7 @@ package storage // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -23,13 +23,13 @@ import ( ) const ( - major = "0" - minor = "4" - patch = "0" + major = "2" + minor = "1" + patch = "1" // Always begin a "tag" with a dash (as per http://semver.org) tag = "-beta" semVerFormat = "%s.%s.%s%s" - userAgentFormat = "Azure-SDK-for-Go/%s;Package arm/%s;API %s" + userAgentFormat = "Azure-SDK-for-Go/%s arm-%s/%s" ) // UserAgent returns the UserAgent string to use when sending http.Requests. diff --git a/vendor/github.com/Azure/azure-sdk-for-go/management/publishSettings.go b/vendor/github.com/Azure/azure-sdk-for-go/management/publishSettings.go index 32bb9724b9eb..2b9d47849670 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/management/publishSettings.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/management/publishSettings.go @@ -7,7 +7,7 @@ import ( "fmt" "io/ioutil" - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/golang.org/x/crypto/pkcs12" + "golang.org/x/crypto/pkcs12" ) // ClientFromPublishSettingsData unmarshalls the contents of a publish settings file diff --git a/vendor/github.com/Azure/azure-sdk-for-go/management/virtualmachine/client.go b/vendor/github.com/Azure/azure-sdk-for-go/management/virtualmachine/client.go index a712b44cc4da..a9fe82755118 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/management/virtualmachine/client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/management/virtualmachine/client.go @@ -209,7 +209,7 @@ func (vm VirtualMachineClient) StartRole(cloudServiceName, deploymentName, roleN return vm.client.SendAzurePostRequest(requestURL, startRoleOperationBytes) } -func (vm VirtualMachineClient) ShutdownRole(cloudServiceName, deploymentName, roleName string) (management.OperationID, error) { +func (vm VirtualMachineClient) ShutdownRole(cloudServiceName, deploymentName, roleName string, postaction PostShutdownAction) (management.OperationID, error) { if cloudServiceName == "" { return "", fmt.Errorf(errParamNotSpecified, "cloudServiceName") } @@ -221,7 +221,8 @@ func (vm VirtualMachineClient) ShutdownRole(cloudServiceName, deploymentName, ro } shutdownRoleOperationBytes, err := xml.Marshal(ShutdownRoleOperation{ - OperationType: "ShutdownRoleOperation", + OperationType: "ShutdownRoleOperation", + PostShutdownAction: postaction, }) if err != nil { return "", err diff --git a/vendor/github.com/Azure/azure-sdk-for-go/management/virtualmachine/entities.go b/vendor/github.com/Azure/azure-sdk-for-go/management/virtualmachine/entities.go index f105ee82fdd1..a826541a785f 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/management/virtualmachine/entities.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/management/virtualmachine/entities.go @@ -451,6 +451,7 @@ const ( // virtual IP address for the Virtual Machine. type PublicIP struct { Name string // Specifies the name of the public IP address. + Address string // Specifies the IP address. IdleTimeoutInMinutes int `xml:",omitempty"` // Specifies the timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. } @@ -468,10 +469,19 @@ type StartRoleOperation struct { OperationType string } +type PostShutdownAction string + +// Enum values for PostShutdownAction +const ( + PostShutdownActionStopped PostShutdownAction = "Stopped" + PostShutdownActionStoppedDeallocated PostShutdownAction = "StoppedDeallocated" +) + // ShutdownRoleOperation contains the information for shutting down a Role. type ShutdownRoleOperation struct { - XMLName xml.Name `xml:"http://schemas.microsoft.com/windowsazure ShutdownRoleOperation"` - OperationType string + XMLName xml.Name `xml:"http://schemas.microsoft.com/windowsazure ShutdownRoleOperation"` + OperationType string + PostShutdownAction PostShutdownAction } // RestartRoleOperation contains the information for restarting a Role. diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/blob.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/blob.go index da1d816fc2fb..8b2b6f69fdde 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/storage/blob.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/blob.go @@ -55,7 +55,51 @@ type ContainerListResponse struct { type Blob struct { Name string `xml:"Name"` Properties BlobProperties `xml:"Properties"` - // TODO (ahmetalpbalkan) Metadata + Metadata BlobMetadata `xml:"Metadata"` +} + +// BlobMetadata is a set of custom name/value pairs. +// +// See https://msdn.microsoft.com/en-us/library/azure/dd179404.aspx +type BlobMetadata map[string]string + +type blobMetadataEntries struct { + Entries []blobMetadataEntry `xml:",any"` +} +type blobMetadataEntry struct { + XMLName xml.Name + Value string `xml:",chardata"` +} + +// UnmarshalXML converts the xml:Metadata into Metadata map +func (bm *BlobMetadata) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { + var entries blobMetadataEntries + if err := d.DecodeElement(&entries, &start); err != nil { + return err + } + for _, entry := range entries.Entries { + if *bm == nil { + *bm = make(BlobMetadata) + } + (*bm)[strings.ToLower(entry.XMLName.Local)] = entry.Value + } + return nil +} + +// MarshalXML implements the xml.Marshaler interface. It encodes +// metadata name/value pairs as they would appear in an Azure +// ListBlobs response. +func (bm BlobMetadata) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + entries := make([]blobMetadataEntry, 0, len(bm)) + for k, v := range bm { + entries = append(entries, blobMetadataEntry{ + XMLName: xml.Name{Local: http.CanonicalHeaderKey(k)}, + Value: v, + }) + } + return enc.EncodeElement(blobMetadataEntries{ + Entries: entries, + }, start) } // BlobProperties contains various properties of a blob @@ -75,6 +119,7 @@ type BlobProperties struct { CopyProgress string `xml:"CopyProgress"` CopyCompletionTime string `xml:"CopyCompletionTime"` CopyStatusDescription string `xml:"CopyStatusDescription"` + LeaseStatus string `xml:"LeaseStatus"` } // BlobListResponse contains the response fields from ListBlobs call. @@ -88,6 +133,16 @@ type BlobListResponse struct { NextMarker string `xml:"NextMarker"` MaxResults int64 `xml:"MaxResults"` Blobs []Blob `xml:"Blobs>Blob"` + + // BlobPrefix is used to traverse blobs as if it were a file system. + // It is returned if ListBlobsParameters.Delimiter is specified. + // The list here can be thought of as "folders" that may contain + // other folders or blobs. + BlobPrefixes []string `xml:"Blobs>BlobPrefix>Name"` + + // Delimiter is used to traverse blobs as if it were a file system. + // It is returned if ListBlobsParameters.Delimiter is specified. + Delimiter string `xml:"Delimiter"` } // ListContainersParameters defines the set of customizable parameters to make a @@ -167,8 +222,9 @@ type BlobType string // Types of page blobs const ( - BlobTypeBlock BlobType = "BlockBlob" - BlobTypePage BlobType = "PageBlob" + BlobTypeBlock BlobType = "BlockBlob" + BlobTypePage BlobType = "PageBlob" + BlobTypeAppend BlobType = "AppendBlob" ) // PageWriteType defines the type updates that are going to be @@ -330,7 +386,6 @@ func (b BlobStorageClient) createContainer(name string, access ContainerAccessTy uri := b.client.getEndpoint(blobServiceName, pathForContainer(name), url.Values{"restype": {"container"}}) headers := b.client.getStandardHeaders() - headers["Content-Length"] = "0" if access != "" { headers["x-ms-blob-public-access"] = string(access) } @@ -447,7 +502,7 @@ func (b BlobStorageClient) GetBlobURL(container, name string) string { // // See https://msdn.microsoft.com/en-us/library/azure/dd179440.aspx func (b BlobStorageClient) GetBlob(container, name string) (io.ReadCloser, error) { - resp, err := b.getBlobRange(container, name, "") + resp, err := b.getBlobRange(container, name, "", nil) if err != nil { return nil, err } @@ -462,8 +517,8 @@ func (b BlobStorageClient) GetBlob(container, name string) (io.ReadCloser, error // string must be in a format like "0-", "10-100" as defined in HTTP 1.1 spec. // // See https://msdn.microsoft.com/en-us/library/azure/dd179440.aspx -func (b BlobStorageClient) GetBlobRange(container, name, bytesRange string) (io.ReadCloser, error) { - resp, err := b.getBlobRange(container, name, bytesRange) +func (b BlobStorageClient) GetBlobRange(container, name, bytesRange string, extraHeaders map[string]string) (io.ReadCloser, error) { + resp, err := b.getBlobRange(container, name, bytesRange, extraHeaders) if err != nil { return nil, err } @@ -474,7 +529,7 @@ func (b BlobStorageClient) GetBlobRange(container, name, bytesRange string) (io. return resp.body, nil } -func (b BlobStorageClient) getBlobRange(container, name, bytesRange string) (*storageResponse, error) { +func (b BlobStorageClient) getBlobRange(container, name, bytesRange string, extraHeaders map[string]string) (*storageResponse, error) { verb := "GET" uri := b.client.getEndpoint(blobServiceName, pathForBlob(container, name), url.Values{}) @@ -482,6 +537,11 @@ func (b BlobStorageClient) getBlobRange(container, name, bytesRange string) (*st if bytesRange != "" { headers["Range"] = fmt.Sprintf("bytes=%s", bytesRange) } + + for k, v := range extraHeaders { + headers[k] = v + } + resp, err := b.client.exec(verb, uri, headers, nil) if err != nil { return nil, err @@ -538,6 +598,7 @@ func (b BlobStorageClient) GetBlobProperties(container, name string) (*BlobPrope CopySource: resp.headers.Get("x-ms-copy-source"), CopyStatus: resp.headers.Get("x-ms-copy-status"), BlobType: BlobType(resp.headers.Get("x-ms-blob-type")), + LeaseStatus: resp.headers.Get("x-ms-lease-status"), }, nil } @@ -549,14 +610,17 @@ func (b BlobStorageClient) GetBlobProperties(container, name string) (*BlobPrope // applications either. // // See https://msdn.microsoft.com/en-us/library/azure/dd179414.aspx -func (b BlobStorageClient) SetBlobMetadata(container, name string, metadata map[string]string) error { +func (b BlobStorageClient) SetBlobMetadata(container, name string, metadata map[string]string, extraHeaders map[string]string) error { params := url.Values{"comp": {"metadata"}} uri := b.client.getEndpoint(blobServiceName, pathForBlob(container, name), params) headers := b.client.getStandardHeaders() for k, v := range metadata { headers[userDefinedMetadataHeaderPrefix+k] = v } - headers["Content-Length"] = "0" + + for k, v := range extraHeaders { + headers[k] = v + } resp, err := b.client.exec("PUT", uri, headers, nil) if err != nil { @@ -731,7 +795,6 @@ func (b BlobStorageClient) PutPageBlob(container, name string, size int64, extra headers := b.client.getStandardHeaders() headers["x-ms-blob-type"] = string(BlobTypePage) headers["x-ms-blob-content-length"] = fmt.Sprintf("%v", size) - headers["Content-Length"] = fmt.Sprintf("%v", 0) for k, v := range extraHeaders { headers[k] = v @@ -751,14 +814,16 @@ func (b BlobStorageClient) PutPageBlob(container, name string, size int64, extra // with 512-byte boundaries and chunk must be of size multiplies by 512. // // See https://msdn.microsoft.com/en-us/library/ee691975.aspx -func (b BlobStorageClient) PutPage(container, name string, startByte, endByte int64, writeType PageWriteType, chunk []byte) error { +func (b BlobStorageClient) PutPage(container, name string, startByte, endByte int64, writeType PageWriteType, chunk []byte, extraHeaders map[string]string) error { path := fmt.Sprintf("%s/%s", container, name) uri := b.client.getEndpoint(blobServiceName, path, url.Values{"comp": {"page"}}) headers := b.client.getStandardHeaders() headers["x-ms-blob-type"] = string(BlobTypePage) headers["x-ms-page-write"] = string(writeType) headers["x-ms-range"] = fmt.Sprintf("bytes=%v-%v", startByte, endByte) - + for k, v := range extraHeaders { + headers[k] = v + } var contentLength int64 var data io.Reader if writeType == PageWriteTypeClear { @@ -801,6 +866,52 @@ func (b BlobStorageClient) GetPageRanges(container, name string) (GetPageRangesR return out, err } +// PutAppendBlob initializes an empty append blob with specified name. An +// append blob must be created using this method before appending blocks. +// +// See https://msdn.microsoft.com/en-us/library/azure/dd179451.aspx +func (b BlobStorageClient) PutAppendBlob(container, name string, extraHeaders map[string]string) error { + path := fmt.Sprintf("%s/%s", container, name) + uri := b.client.getEndpoint(blobServiceName, path, url.Values{}) + headers := b.client.getStandardHeaders() + headers["x-ms-blob-type"] = string(BlobTypeAppend) + + for k, v := range extraHeaders { + headers[k] = v + } + + resp, err := b.client.exec("PUT", uri, headers, nil) + if err != nil { + return err + } + defer resp.body.Close() + + return checkRespCode(resp.statusCode, []int{http.StatusCreated}) +} + +// AppendBlock appends a block to an append blob. +// +// See https://msdn.microsoft.com/en-us/library/azure/mt427365.aspx +func (b BlobStorageClient) AppendBlock(container, name string, chunk []byte, extraHeaders map[string]string) error { + path := fmt.Sprintf("%s/%s", container, name) + uri := b.client.getEndpoint(blobServiceName, path, url.Values{"comp": {"appendblock"}}) + headers := b.client.getStandardHeaders() + headers["x-ms-blob-type"] = string(BlobTypeAppend) + headers["Content-Length"] = fmt.Sprintf("%v", len(chunk)) + + for k, v := range extraHeaders { + headers[k] = v + } + + resp, err := b.client.exec("PUT", uri, headers, bytes.NewReader(chunk)) + if err != nil { + return err + } + defer resp.body.Close() + + return checkRespCode(resp.statusCode, []int{http.StatusCreated}) +} + // CopyBlob starts a blob copy operation and waits for the operation to // complete. sourceBlob parameter must be a canonical URL to the blob (can be // obtained using GetBlobURL method.) There is no SLA on blob copy and therefore @@ -820,7 +931,6 @@ func (b BlobStorageClient) startBlobCopy(container, name, sourceBlob string) (st uri := b.client.getEndpoint(blobServiceName, pathForBlob(container, name), url.Values{}) headers := b.client.getStandardHeaders() - headers["Content-Length"] = "0" headers["x-ms-copy-source"] = sourceBlob resp, err := b.client.exec("PUT", uri, headers, nil) @@ -869,8 +979,8 @@ func (b BlobStorageClient) waitForBlobCopy(container, name, copyID string) error // DeleteBlob deletes the given blob from the specified container. // If the blob does not exists at the time of the Delete Blob operation, it // returns error. See https://msdn.microsoft.com/en-us/library/azure/dd179413.aspx -func (b BlobStorageClient) DeleteBlob(container, name string) error { - resp, err := b.deleteBlob(container, name) +func (b BlobStorageClient) DeleteBlob(container, name string, extraHeaders map[string]string) error { + resp, err := b.deleteBlob(container, name, extraHeaders) if err != nil { return err } @@ -882,8 +992,8 @@ func (b BlobStorageClient) DeleteBlob(container, name string) error { // blob is deleted with this call, returns true. Otherwise returns false. // // See https://msdn.microsoft.com/en-us/library/azure/dd179413.aspx -func (b BlobStorageClient) DeleteBlobIfExists(container, name string) (bool, error) { - resp, err := b.deleteBlob(container, name) +func (b BlobStorageClient) DeleteBlobIfExists(container, name string, extraHeaders map[string]string) (bool, error) { + resp, err := b.deleteBlob(container, name, extraHeaders) if resp != nil && (resp.statusCode == http.StatusAccepted || resp.statusCode == http.StatusNotFound) { return resp.statusCode == http.StatusAccepted, nil } @@ -891,10 +1001,13 @@ func (b BlobStorageClient) DeleteBlobIfExists(container, name string) (bool, err return false, err } -func (b BlobStorageClient) deleteBlob(container, name string) (*storageResponse, error) { +func (b BlobStorageClient) deleteBlob(container, name string, extraHeaders map[string]string) (*storageResponse, error) { verb := "DELETE" uri := b.client.getEndpoint(blobServiceName, pathForBlob(container, name), url.Values{}) headers := b.client.getStandardHeaders() + for k, v := range extraHeaders { + headers[k] = v + } return b.client.exec(verb, uri, headers, nil) } @@ -923,7 +1036,7 @@ func (b BlobStorageClient) GetBlobSASURI(container, name string, expiry time.Tim if err != nil { return "", err } - signedExpiry := expiry.Format(time.RFC3339) + signedExpiry := expiry.UTC().Format(time.RFC3339) signedResource := "b" stringToSign, err := blobSASStringToSign(b.client.apiVersion, canonicalizedResource, signedExpiry, signedPermissions) @@ -951,6 +1064,10 @@ func (b BlobStorageClient) GetBlobSASURI(container, name string, expiry time.Tim func blobSASStringToSign(signedVersion, canonicalizedResource, signedExpiry, signedPermissions string) (string, error) { var signedStart, signedIdentifier, rscc, rscd, rsce, rscl, rsct string + if signedVersion >= "2015-02-21" { + canonicalizedResource = "/blob" + canonicalizedResource + } + // reference: http://msdn.microsoft.com/en-us/library/azure/dn140255.aspx if signedVersion >= "2013-08-15" { return fmt.Sprintf("%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s", signedPermissions, signedStart, signedExpiry, canonicalizedResource, signedIdentifier, signedVersion, rscc, rscd, rsce, rscl, rsct), nil diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/client.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/client.go index 0305e90d8dc4..41cdb25fe772 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/storage/client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/client.go @@ -4,6 +4,7 @@ package storage import ( "bytes" "encoding/base64" + "encoding/json" "encoding/xml" "errors" "fmt" @@ -24,7 +25,7 @@ const ( // DefaultAPIVersion is the Azure Storage API version string used when a // basic client is created. - DefaultAPIVersion = "2014-02-14" + DefaultAPIVersion = "2015-02-21" defaultUseHTTPS = true @@ -37,6 +38,10 @@ const ( // Client is the object that needs to be constructed to perform // operations on the storage account. type Client struct { + // HTTPClient is the http.Client used to initiate API + // requests. If it is nil, http.DefaultClient is used. + HTTPClient *http.Client + accountName string accountKey []byte useHTTPS bool @@ -50,6 +55,11 @@ type storageResponse struct { body io.ReadCloser } +type odataResponse struct { + storageResponse + odata odataErrorMessage +} + // AzureStorageServiceError contains fields of the error response from // Azure Storage Service REST API. See https://msdn.microsoft.com/en-us/library/azure/dd179382.aspx // Some fields might be specific to certain calls. @@ -64,6 +74,20 @@ type AzureStorageServiceError struct { RequestID string } +type odataErrorMessageMessage struct { + Lang string `json:"lang"` + Value string `json:"value"` +} + +type odataErrorMessageInternal struct { + Code string `json:"code"` + Message odataErrorMessageMessage `json:"message"` +} + +type odataErrorMessage struct { + Err odataErrorMessageInternal `json:"odata.error"` +} + // UnexpectedStatusCodeError is returned when a storage service responds with neither an error // nor with an HTTP status code indicating success. type UnexpectedStatusCodeError struct { @@ -162,6 +186,12 @@ func (c Client) GetQueueService() QueueServiceClient { return QueueServiceClient{c} } +// GetTableService returns a TableServiceClient which can operate on the table +// service of the storage account. +func (c Client) GetTableService() TableServiceClient { + return TableServiceClient{c} +} + // GetFileService returns a FileServiceClient which can operate on the file // service of the storage account. func (c Client) GetFileService() FileServiceClient { @@ -224,6 +254,22 @@ func (c Client) buildCanonicalizedHeader(headers map[string]string) string { return ch } +func (c Client) buildCanonicalizedResourceTable(uri string) (string, error) { + errMsg := "buildCanonicalizedResourceTable error: %s" + u, err := url.Parse(uri) + if err != nil { + return "", fmt.Errorf(errMsg, err.Error()) + } + + cr := "/" + c.accountName + + if len(u.Path) > 0 { + cr += u.Path + } + + return cr, nil +} + func (c Client) buildCanonicalizedResource(uri string) (string, error) { errMsg := "buildCanonicalizedResource error: %s" u, err := url.Parse(uri) @@ -232,6 +278,7 @@ func (c Client) buildCanonicalizedResource(uri string) (string, error) { } cr := "/" + c.accountName + if len(u.Path) > 0 { cr += u.Path } @@ -262,15 +309,20 @@ func (c Client) buildCanonicalizedResource(uri string) (string, error) { } } } + return cr, nil } func (c Client) buildCanonicalizedString(verb string, headers map[string]string, canonicalizedResource string) string { + contentLength := headers["Content-Length"] + if contentLength == "0" { + contentLength = "" + } canonicalizedString := fmt.Sprintf("%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s", verb, headers["Content-Encoding"], headers["Content-Language"], - headers["Content-Length"], + contentLength, headers["Content-MD5"], headers["Content-Type"], headers["Date"], @@ -314,7 +366,11 @@ func (c Client) exec(verb, url string, headers map[string]string, body io.Reader for k, v := range headers { req.Header.Add(k, v) } - httpClient := http.Client{} + + httpClient := c.HTTPClient + if httpClient == nil { + httpClient = http.DefaultClient + } resp, err := httpClient.Do(req) if err != nil { return nil, err @@ -352,6 +408,70 @@ func (c Client) exec(verb, url string, headers map[string]string, body io.Reader body: resp.Body}, nil } +func (c Client) execInternalJSON(verb, url string, headers map[string]string, body io.Reader) (*odataResponse, error) { + req, err := http.NewRequest(verb, url, body) + for k, v := range headers { + req.Header.Add(k, v) + } + + httpClient := c.HTTPClient + if httpClient == nil { + httpClient = http.DefaultClient + } + + resp, err := httpClient.Do(req) + if err != nil { + return nil, err + } + + respToRet := &odataResponse{} + respToRet.body = resp.Body + respToRet.statusCode = resp.StatusCode + respToRet.headers = resp.Header + + statusCode := resp.StatusCode + if statusCode >= 400 && statusCode <= 505 { + var respBody []byte + respBody, err = readResponseBody(resp) + if err != nil { + return nil, err + } + + if len(respBody) == 0 { + // no error in response body + err = fmt.Errorf("storage: service returned without a response body (%d)", resp.StatusCode) + return respToRet, err + } + // try unmarshal as odata.error json + err = json.Unmarshal(respBody, &respToRet.odata) + return respToRet, err + } + + return respToRet, nil +} + +func (c Client) createSharedKeyLite(url string, headers map[string]string) (string, error) { + can, err := c.buildCanonicalizedResourceTable(url) + + if err != nil { + return "", err + } + strToSign := headers["x-ms-date"] + "\n" + can + + hmac := c.computeHmac256(strToSign) + return fmt.Sprintf("SharedKeyLite %s:%s", c.accountName, hmac), nil +} + +func (c Client) execTable(verb, url string, headers map[string]string, body io.Reader) (*odataResponse, error) { + var err error + headers["Authorization"], err = c.createSharedKeyLite(url, headers) + if err != nil { + return nil, err + } + + return c.execInternalJSON(verb, url, headers, body) +} + func readResponseBody(resp *http.Response) ([]byte, error) { defer resp.Body.Close() out, err := ioutil.ReadAll(resp.Body) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/file.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/file.go index 089d144935ad..ede4e21be5c6 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/storage/file.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/file.go @@ -49,7 +49,6 @@ func (f FileServiceClient) CreateShareIfNotExists(name string) (bool, error) { func (f FileServiceClient) createShare(name string) (*storageResponse, error) { uri := f.client.getEndpoint(fileServiceName, pathForFileShare(name), url.Values{"restype": {"share"}}) headers := f.client.getStandardHeaders() - headers["Content-Length"] = "0" return f.client.exec("PUT", uri, headers, nil) } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/queue.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/queue.go index 015f1d568930..3ecf4aca0d21 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/storage/queue.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/queue.go @@ -134,7 +134,6 @@ type QueueMetadataResponse struct { func (c QueueServiceClient) SetMetadata(name string, metadata map[string]string) error { uri := c.client.getEndpoint(queueServiceName, pathForQueue(name), url.Values{"comp": []string{"metadata"}}) headers := c.client.getStandardHeaders() - headers["Content-Length"] = "0" for k, v := range metadata { headers[userDefinedMetadataHeaderPrefix+k] = v } @@ -195,7 +194,6 @@ func (c QueueServiceClient) GetMetadata(name string) (QueueMetadataResponse, err func (c QueueServiceClient) CreateQueue(name string) error { uri := c.client.getEndpoint(queueServiceName, pathForQueue(name), url.Values{}) headers := c.client.getStandardHeaders() - headers["Content-Length"] = "0" resp, err := c.client.exec("PUT", uri, headers, nil) if err != nil { return err diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/table.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/table.go new file mode 100644 index 000000000000..39e997503552 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/table.go @@ -0,0 +1,129 @@ +package storage + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + "net/url" +) + +// TableServiceClient contains operations for Microsoft Azure Table Storage +// Service. +type TableServiceClient struct { + client Client +} + +// AzureTable is the typedef of the Azure Table name +type AzureTable string + +const ( + tablesURIPath = "/Tables" +) + +type createTableRequest struct { + TableName string `json:"TableName"` +} + +func pathForTable(table AzureTable) string { return fmt.Sprintf("%s", table) } + +func (c *TableServiceClient) getStandardHeaders() map[string]string { + return map[string]string{ + "x-ms-version": "2015-02-21", + "x-ms-date": currentTimeRfc1123Formatted(), + "Accept": "application/json;odata=nometadata", + "Accept-Charset": "UTF-8", + "Content-Type": "application/json", + } +} + +// QueryTables returns the tables created in the +// *TableServiceClient storage account. +func (c *TableServiceClient) QueryTables() ([]AzureTable, error) { + uri := c.client.getEndpoint(tableServiceName, tablesURIPath, url.Values{}) + + headers := c.getStandardHeaders() + headers["Content-Length"] = "0" + + resp, err := c.client.execTable("GET", uri, headers, nil) + if err != nil { + return nil, err + } + defer resp.body.Close() + + if err := checkRespCode(resp.statusCode, []int{http.StatusOK}); err != nil { + return nil, err + } + + buf := new(bytes.Buffer) + buf.ReadFrom(resp.body) + + var respArray queryTablesResponse + if err := json.Unmarshal(buf.Bytes(), &respArray); err != nil { + return nil, err + } + + s := make([]AzureTable, len(respArray.TableName)) + for i, elem := range respArray.TableName { + s[i] = AzureTable(elem.TableName) + } + + return s, nil +} + +// CreateTable creates the table given the specific +// name. This function fails if the name is not compliant +// with the specification or the tables already exists. +func (c *TableServiceClient) CreateTable(table AzureTable) error { + uri := c.client.getEndpoint(tableServiceName, tablesURIPath, url.Values{}) + + headers := c.getStandardHeaders() + + req := createTableRequest{TableName: string(table)} + buf := new(bytes.Buffer) + + if err := json.NewEncoder(buf).Encode(req); err != nil { + return err + } + + headers["Content-Length"] = fmt.Sprintf("%d", buf.Len()) + + resp, err := c.client.execTable("POST", uri, headers, buf) + + if err != nil { + return err + } + defer resp.body.Close() + + if err := checkRespCode(resp.statusCode, []int{http.StatusCreated}); err != nil { + return err + } + + return nil +} + +// DeleteTable deletes the table given the specific +// name. This function fails if the table is not present. +// Be advised: DeleteTable deletes all the entries +// that may be present. +func (c *TableServiceClient) DeleteTable(table AzureTable) error { + uri := c.client.getEndpoint(tableServiceName, tablesURIPath, url.Values{}) + uri += fmt.Sprintf("('%s')", string(table)) + + headers := c.getStandardHeaders() + + headers["Content-Length"] = "0" + + resp, err := c.client.execTable("DELETE", uri, headers, nil) + + if err != nil { + return err + } + defer resp.body.Close() + + if err := checkRespCode(resp.statusCode, []int{http.StatusNoContent}); err != nil { + return err + + } + return nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/table_entities.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/table_entities.go new file mode 100644 index 000000000000..c81393e5f506 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/table_entities.go @@ -0,0 +1,351 @@ +package storage + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "reflect" +) + +const ( + partitionKeyNode = "PartitionKey" + rowKeyNode = "RowKey" + tag = "table" + tagIgnore = "-" + continuationTokenPartitionKeyHeader = "X-Ms-Continuation-Nextpartitionkey" + continuationTokenRowHeader = "X-Ms-Continuation-Nextrowkey" + maxTopParameter = 1000 +) + +type queryTablesResponse struct { + TableName []struct { + TableName string `json:"TableName"` + } `json:"value"` +} + +const ( + tableOperationTypeInsert = iota + tableOperationTypeUpdate = iota + tableOperationTypeMerge = iota + tableOperationTypeInsertOrReplace = iota + tableOperationTypeInsertOrMerge = iota +) + +type tableOperation int + +// TableEntity interface specifies +// the functions needed to support +// marshaling and unmarshaling into +// Azure Tables. The struct must only contain +// simple types because Azure Tables do not +// support hierarchy. +type TableEntity interface { + PartitionKey() string + RowKey() string + SetPartitionKey(string) error + SetRowKey(string) error +} + +// ContinuationToken is an opaque (ie not useful to inspect) +// struct that Get... methods can return if there are more +// entries to be returned than the ones already +// returned. Just pass it to the same function to continue +// receiving the remaining entries. +type ContinuationToken struct { + NextPartitionKey string + NextRowKey string +} + +type getTableEntriesResponse struct { + Elements []map[string]interface{} `json:"value"` +} + +// QueryTableEntities queries the specified table and returns the unmarshaled +// entities of type retType. +// top parameter limits the returned entries up to top. Maximum top +// allowed by Azure API is 1000. In case there are more than top entries to be +// returned the function will return a non nil *ContinuationToken. You can call the +// same function again passing the received ContinuationToken as previousContToken +// parameter in order to get the following entries. The query parameter +// is the odata query. To retrieve all the entries pass the empty string. +// The function returns a pointer to a TableEntity slice, the *ContinuationToken +// if there are more entries to be returned and an error in case something went +// wrong. +// +// Example: +// entities, cToken, err = tSvc.QueryTableEntities("table", cToken, reflect.TypeOf(entity), 20, "") +func (c *TableServiceClient) QueryTableEntities(tableName AzureTable, previousContToken *ContinuationToken, retType reflect.Type, top int, query string) ([]TableEntity, *ContinuationToken, error) { + if top > maxTopParameter { + return nil, nil, fmt.Errorf("top accepts at maximum %d elements. Requested %d instead", maxTopParameter, top) + } + + uri := c.client.getEndpoint(tableServiceName, pathForTable(tableName), url.Values{}) + uri += fmt.Sprintf("?$top=%d", top) + if query != "" { + uri += fmt.Sprintf("&$filter=%s", url.QueryEscape(query)) + } + + if previousContToken != nil { + uri += fmt.Sprintf("&NextPartitionKey=%s&NextRowKey=%s", previousContToken.NextPartitionKey, previousContToken.NextRowKey) + } + + headers := c.getStandardHeaders() + + headers["Content-Length"] = "0" + + resp, err := c.client.execTable("GET", uri, headers, nil) + + contToken := extractContinuationTokenFromHeaders(resp.headers) + + if err != nil { + return nil, contToken, err + } + defer resp.body.Close() + + if err := checkRespCode(resp.statusCode, []int{http.StatusOK}); err != nil { + return nil, contToken, err + } + + retEntries, err := deserializeEntity(retType, resp.body) + if err != nil { + return nil, contToken, err + } + + return retEntries, contToken, nil +} + +// InsertEntity inserts an entity in the specified table. +// The function fails if there is an entity with the same +// PartitionKey and RowKey in the table. +func (c *TableServiceClient) InsertEntity(table AzureTable, entity TableEntity) error { + var err error + + if sc, err := c.execTable(table, entity, false, "POST"); err != nil { + return checkRespCode(sc, []int{http.StatusCreated}) + } + + return err +} + +func (c *TableServiceClient) execTable(table AzureTable, entity TableEntity, specifyKeysInURL bool, method string) (int, error) { + uri := c.client.getEndpoint(tableServiceName, pathForTable(table), url.Values{}) + if specifyKeysInURL { + uri += fmt.Sprintf("(PartitionKey='%s',RowKey='%s')", url.QueryEscape(entity.PartitionKey()), url.QueryEscape(entity.RowKey())) + } + + headers := c.getStandardHeaders() + + var buf bytes.Buffer + + if err := injectPartitionAndRowKeys(entity, &buf); err != nil { + return 0, err + } + + headers["Content-Length"] = fmt.Sprintf("%d", buf.Len()) + + var err error + var resp *odataResponse + + resp, err = c.client.execTable(method, uri, headers, &buf) + + if err != nil { + return 0, err + } + + defer resp.body.Close() + + return resp.statusCode, nil +} + +// UpdateEntity updates the contents of an entity with the +// one passed as parameter. The function fails if there is no entity +// with the same PartitionKey and RowKey in the table. +func (c *TableServiceClient) UpdateEntity(table AzureTable, entity TableEntity) error { + var err error + + if sc, err := c.execTable(table, entity, true, "PUT"); err != nil { + return checkRespCode(sc, []int{http.StatusNoContent}) + } + return err +} + +// MergeEntity merges the contents of an entity with the +// one passed as parameter. +// The function fails if there is no entity +// with the same PartitionKey and RowKey in the table. +func (c *TableServiceClient) MergeEntity(table AzureTable, entity TableEntity) error { + var err error + + if sc, err := c.execTable(table, entity, true, "MERGE"); err != nil { + return checkRespCode(sc, []int{http.StatusNoContent}) + } + return err +} + +// DeleteEntityWithoutCheck deletes the entity matching by +// PartitionKey and RowKey. There is no check on IfMatch +// parameter so the entity is always deleted. +// The function fails if there is no entity +// with the same PartitionKey and RowKey in the table. +func (c *TableServiceClient) DeleteEntityWithoutCheck(table AzureTable, entity TableEntity) error { + return c.DeleteEntity(table, entity, "*") +} + +// DeleteEntity deletes the entity matching by +// PartitionKey, RowKey and ifMatch field. +// The function fails if there is no entity +// with the same PartitionKey and RowKey in the table or +// the ifMatch is different. +func (c *TableServiceClient) DeleteEntity(table AzureTable, entity TableEntity, ifMatch string) error { + uri := c.client.getEndpoint(tableServiceName, pathForTable(table), url.Values{}) + uri += fmt.Sprintf("(PartitionKey='%s',RowKey='%s')", url.QueryEscape(entity.PartitionKey()), url.QueryEscape(entity.RowKey())) + + headers := c.getStandardHeaders() + + headers["Content-Length"] = "0" + headers["If-Match"] = ifMatch + + resp, err := c.client.execTable("DELETE", uri, headers, nil) + + if err != nil { + return err + } + defer resp.body.Close() + + if err := checkRespCode(resp.statusCode, []int{http.StatusNoContent}); err != nil { + return err + } + + return nil +} + +// InsertOrReplaceEntity inserts an entity in the specified table +// or replaced the existing one. +func (c *TableServiceClient) InsertOrReplaceEntity(table AzureTable, entity TableEntity) error { + var err error + + if sc, err := c.execTable(table, entity, true, "PUT"); err != nil { + return checkRespCode(sc, []int{http.StatusNoContent}) + } + return err +} + +// InsertOrMergeEntity inserts an entity in the specified table +// or merges the existing one. +func (c *TableServiceClient) InsertOrMergeEntity(table AzureTable, entity TableEntity) error { + var err error + + if sc, err := c.execTable(table, entity, true, "MERGE"); err != nil { + return checkRespCode(sc, []int{http.StatusNoContent}) + } + return err +} + +func injectPartitionAndRowKeys(entity TableEntity, buf *bytes.Buffer) error { + if err := json.NewEncoder(buf).Encode(entity); err != nil { + return err + } + + dec := make(map[string]interface{}) + if err := json.NewDecoder(buf).Decode(&dec); err != nil { + return err + } + + // Inject PartitionKey and RowKey + dec[partitionKeyNode] = entity.PartitionKey() + dec[rowKeyNode] = entity.RowKey() + + // Remove tagged fields + // The tag is defined in the const section + // This is useful to avoid storing the PartitionKey and RowKey twice. + numFields := reflect.ValueOf(entity).Elem().NumField() + for i := 0; i < numFields; i++ { + f := reflect.ValueOf(entity).Elem().Type().Field(i) + + if f.Tag.Get(tag) == tagIgnore { + // we must look for its JSON name in the dictionary + // as the user can rename it using a tag + jsonName := f.Name + if f.Tag.Get("json") != "" { + jsonName = f.Tag.Get("json") + } + delete(dec, jsonName) + } + } + + buf.Reset() + + if err := json.NewEncoder(buf).Encode(&dec); err != nil { + return err + } + + return nil +} + +func deserializeEntity(retType reflect.Type, reader io.Reader) ([]TableEntity, error) { + buf := new(bytes.Buffer) + + var ret getTableEntriesResponse + if err := json.NewDecoder(reader).Decode(&ret); err != nil { + return nil, err + } + + tEntries := make([]TableEntity, len(ret.Elements)) + + for i, entry := range ret.Elements { + + buf.Reset() + if err := json.NewEncoder(buf).Encode(entry); err != nil { + return nil, err + } + + dec := make(map[string]interface{}) + if err := json.NewDecoder(buf).Decode(&dec); err != nil { + return nil, err + } + + var pKey, rKey string + // strip pk and rk + for key, val := range dec { + switch key { + case partitionKeyNode: + pKey = val.(string) + case rowKeyNode: + rKey = val.(string) + } + } + + delete(dec, partitionKeyNode) + delete(dec, rowKeyNode) + + buf.Reset() + if err := json.NewEncoder(buf).Encode(dec); err != nil { + return nil, err + } + + // Create a empty retType instance + tEntries[i] = reflect.New(retType.Elem()).Interface().(TableEntity) + // Popolate it with the values + if err := json.NewDecoder(buf).Decode(&tEntries[i]); err != nil { + return nil, err + } + + // Reset PartitionKey and RowKey + tEntries[i].SetPartitionKey(pKey) + tEntries[i].SetRowKey(rKey) + } + + return tEntries, nil +} + +func extractContinuationTokenFromHeaders(h http.Header) *ContinuationToken { + ct := ContinuationToken{h.Get(continuationTokenPartitionKeyHeader), h.Get(continuationTokenRowHeader)} + + if ct.NextPartitionKey != "" && ct.NextRowKey != "" { + return &ct + } + return nil +} diff --git a/vendor/github.com/Azure/go-autorest/LICENSE b/vendor/github.com/Azure/go-autorest/LICENSE new file mode 100644 index 000000000000..b9d6a27ea92e --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/LICENSE @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2015 Microsoft Corporation + + 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. diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/autorest.go b/vendor/github.com/Azure/go-autorest/autorest/autorest.go similarity index 53% rename from vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/autorest.go rename to vendor/github.com/Azure/go-autorest/autorest/autorest.go index c50d13c9c2dd..9804f401ef9f 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/autorest.go +++ b/vendor/github.com/Azure/go-autorest/autorest/autorest.go @@ -62,8 +62,11 @@ import ( ) const ( - headerLocation = "Location" - headerRetryAfter = "Retry-After" + // HeaderLocation specifies the HTTP Location header. + HeaderLocation = "Location" + + // HeaderRetryAfter specifies the HTTP Retry-After header. + HeaderRetryAfter = "Retry-After" ) // ResponseHasStatusCode returns true if the status code in the HTTP Response is in the passed set @@ -72,48 +75,15 @@ func ResponseHasStatusCode(resp *http.Response, codes ...int) bool { return containsInt(codes, resp.StatusCode) } -// ResponseRequiresPolling returns true if the passed http.Response requires polling follow-up -// request (as determined by the status code being in the passed set, which defaults to HTTP 202 -// Accepted). -func ResponseRequiresPolling(resp *http.Response, codes ...int) bool { - if resp.StatusCode == http.StatusOK { - return false - } - - if len(codes) == 0 { - codes = []int{http.StatusAccepted} - } - - return ResponseHasStatusCode(resp, codes...) -} - -// NewPollingRequest allocates and returns a new http.Request to poll for the passed response. If -// it successfully creates the request, it will also close the body of the passed response, -// otherwise the body remains open. -func NewPollingRequest(resp *http.Response, authorizer Authorizer) (*http.Request, error) { - location := GetPollingLocation(resp) - if location == "" { - return nil, NewErrorWithStatusCode("autorest", "NewPollingRequest", resp.StatusCode, "Location header missing from response that requires polling") - } - - req, err := Prepare(&http.Request{}, - AsGet(), - WithBaseURL(location), - authorizer.WithAuthorization()) - if err != nil { - return nil, NewErrorWithError(err, "autorest", "NewPollingRequest", UndefinedStatusCode, "Failure creating poll request to %s", location) - } - - Respond(resp, - ByClosing()) - - return req, nil +// GetLocation retrieves the URL from the Location header of the passed response. +func GetLocation(resp *http.Response) string { + return resp.Header.Get(HeaderLocation) } -// GetPollingDelay extracts the polling delay from the Retry-After header of the passed response. If +// GetRetryAfter extracts the retry delay from the Retry-After header of the passed response. If // the header is absent or is malformed, it will return the supplied default delay time.Duration. -func GetPollingDelay(resp *http.Response, defaultDelay time.Duration) time.Duration { - retry := resp.Header.Get(headerRetryAfter) +func GetRetryAfter(resp *http.Response, defaultDelay time.Duration) time.Duration { + retry := resp.Header.Get(HeaderRetryAfter) if retry == "" { return defaultDelay } @@ -126,38 +96,19 @@ func GetPollingDelay(resp *http.Response, defaultDelay time.Duration) time.Durat return d } -// GetPollingLocation retrieves the polling URL from the Location header of the passed response. -func GetPollingLocation(resp *http.Response) string { - return resp.Header.Get(headerLocation) -} - -// PollForAttempts will retry the passed http.Request until it receives an HTTP status code outside -// the passed set or has made the specified number of attempts. The set of status codes defaults to -// HTTP 202 Accepted. -func PollForAttempts(s Sender, req *http.Request, defaultDelay time.Duration, attempts int, codes ...int) (*http.Response, error) { - return SendWithSender( - decorateForPolling(s, defaultDelay, codes...), - req, - DoRetryForAttempts(attempts, time.Duration(0))) -} - -// PollForDuration will retry the passed http.Request until it receives an HTTP status code outside -// the passed set or the total time meets or exceeds the specified duration. The set of status codes -// defaults to HTTP 202 Accepted. -func PollForDuration(s Sender, req *http.Request, defaultDelay time.Duration, total time.Duration, codes ...int) (*http.Response, error) { - return SendWithSender( - decorateForPolling(s, defaultDelay, codes...), - req, - DoRetryForDuration(total, time.Duration(0))) -} +// NewPollingRequest allocates and returns a new http.Request to poll for the passed response. +func NewPollingRequest(resp *http.Response, cancel <-chan struct{}) (*http.Request, error) { + location := GetLocation(resp) + if location == "" { + return nil, NewErrorWithResponse("autorest", "NewPollingRequest", resp, "Location header missing from response that requires polling") + } -func decorateForPolling(s Sender, defaultDelay time.Duration, codes ...int) Sender { - if len(codes) == 0 { - codes = []int{http.StatusAccepted} + req, err := Prepare(&http.Request{Cancel: cancel}, + AsGet(), + WithBaseURL(location)) + if err != nil { + return nil, NewErrorWithError(err, "autorest", "NewPollingRequest", nil, "Failure creating poll request to %s", location) } - return DecorateSender(s, - AfterRetryDelay(defaultDelay), - DoErrorIfStatusCode(codes...), - DoCloseIfError()) + return req, nil } diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/async.go b/vendor/github.com/Azure/go-autorest/autorest/azure/async.go new file mode 100644 index 000000000000..93fa25b99742 --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/async.go @@ -0,0 +1,306 @@ +package azure + +import ( + "bytes" + "fmt" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/date" + "io/ioutil" + "net/http" + "strings" + "time" +) + +const ( + headerAsyncOperation = "Azure-AsyncOperation" +) + +const ( + methodDelete = "DELETE" + methodPatch = "PATCH" + methodPost = "POST" + methodPut = "PUT" + methodGet = "GET" + + operationInProgress string = "InProgress" + operationCanceled string = "Canceled" + operationFailed string = "Failed" + operationSucceeded string = "Succeeded" +) + +// DoPollForAsynchronous returns a SendDecorator that polls if the http.Response is for an Azure +// long-running operation. It will delay between requests for the duration specified in the +// RetryAfter header or, if the header is absent, the passed delay. Polling may be canceled by +// closing the optional channel on the http.Request. +func DoPollForAsynchronous(delay time.Duration) autorest.SendDecorator { + return func(s autorest.Sender) autorest.Sender { + return autorest.SenderFunc(func(r *http.Request) (resp *http.Response, err error) { + resp, err = s.Do(r) + if err != nil { + return resp, err + } + pollingCodes := []int{http.StatusAccepted, http.StatusCreated, http.StatusOK} + if !autorest.ResponseHasStatusCode(resp, pollingCodes...) { + return resp, nil + } + + ps := pollingState{} + for err == nil { + err = updatePollingState(resp, &ps) + if err != nil { + break + } + if ps.hasTerminated() { + if !ps.hasSucceeded() { + err = ps + } + break + } + + r, err = newPollingRequest(resp, ps) + if err != nil { + return resp, err + } + + resp, err = autorest.SendWithSender(s, r, + autorest.AfterDelay(autorest.GetRetryAfter(resp, delay))) + } + + return resp, err + }) + } +} + +func getAsyncOperation(resp *http.Response) string { + return resp.Header.Get(http.CanonicalHeaderKey(headerAsyncOperation)) +} + +func hasSucceeded(state string) bool { + return state == operationSucceeded +} + +func hasTerminated(state string) bool { + switch state { + case operationCanceled, operationFailed, operationSucceeded: + return true + default: + return false + } +} + +func hasFailed(state string) bool { + return state == operationFailed +} + +type provisioningTracker interface { + state() string + hasSucceeded() bool + hasTerminated() bool +} + +type operationResource struct { + // Note: + // The specification states services should return the "id" field. However some return it as + // "operationId". + ID string `json:"id"` + OperationID string `json:"operationId"` + Name string `json:"name"` + Status string `json:"status"` + Properties map[string]interface{} `json:"properties"` + OperationError ServiceError `json:"error"` + StartTime date.Time `json:"startTime"` + EndTime date.Time `json:"endTime"` + PercentComplete float64 `json:"percentComplete"` +} + +func (or operationResource) state() string { + return or.Status +} + +func (or operationResource) hasSucceeded() bool { + return hasSucceeded(or.state()) +} + +func (or operationResource) hasTerminated() bool { + return hasTerminated(or.state()) +} + +type provisioningProperties struct { + ProvisioningState string `json:"provisioningState"` +} + +type provisioningStatus struct { + Properties provisioningProperties `json:"properties,omitempty"` + ProvisioningError ServiceError `json:"error,omitempty"` +} + +func (ps provisioningStatus) state() string { + return ps.Properties.ProvisioningState +} + +func (ps provisioningStatus) hasSucceeded() bool { + return hasSucceeded(ps.state()) +} + +func (ps provisioningStatus) hasTerminated() bool { + return hasTerminated(ps.state()) +} + +func (ps provisioningStatus) hasProvisioningError() bool { + return ps.ProvisioningError != ServiceError{} +} + +type pollingResponseFormat string + +const ( + usesOperationResponse pollingResponseFormat = "OperationResponse" + usesProvisioningStatus pollingResponseFormat = "ProvisioningStatus" + formatIsUnknown pollingResponseFormat = "" +) + +type pollingState struct { + responseFormat pollingResponseFormat + uri string + state string + code string + message string +} + +func (ps pollingState) hasSucceeded() bool { + return hasSucceeded(ps.state) +} + +func (ps pollingState) hasTerminated() bool { + return hasTerminated(ps.state) +} + +func (ps pollingState) hasFailed() bool { + return hasFailed(ps.state) +} + +func (ps pollingState) Error() string { + return fmt.Sprintf("Long running operation terminated with status '%s': Code=%q Message=%q", ps.state, ps.code, ps.message) +} + +// updatePollingState maps the operation status -- retrieved from either a provisioningState +// field, the status field of an OperationResource, or inferred from the HTTP status code -- +// into a well-known states. Since the process begins from the initial request, the state +// always comes from either a the provisioningState returned or is inferred from the HTTP +// status code. Subsequent requests will read an Azure OperationResource object if the +// service initially returned the Azure-AsyncOperation header. The responseFormat field notes +// the expected response format. +func updatePollingState(resp *http.Response, ps *pollingState) error { + // Determine the response shape + // -- The first response will always be a provisioningStatus response; only the polling requests, + // depending on the header returned, may be something otherwise. + var pt provisioningTracker + if ps.responseFormat == usesOperationResponse { + pt = &operationResource{} + } else { + pt = &provisioningStatus{} + } + + // If this is the first request (that is, the polling response shape is unknown), determine how + // to poll and what to expect + if ps.responseFormat == formatIsUnknown { + req := resp.Request + if req == nil { + return autorest.NewError("azure", "updatePollingState", "Azure Polling Error - Original HTTP request is missing") + } + + // Prefer the Azure-AsyncOperation header + ps.uri = getAsyncOperation(resp) + if ps.uri != "" { + ps.responseFormat = usesOperationResponse + } else { + ps.responseFormat = usesProvisioningStatus + } + + // Else, use the Location header + if ps.uri == "" { + ps.uri = autorest.GetLocation(resp) + } + + // Lastly, requests against an existing resource, use the last request URI + if ps.uri == "" { + m := strings.ToUpper(req.Method) + if m == methodPatch || m == methodPut || m == methodGet { + ps.uri = req.URL.String() + } + } + } + + // Read and interpret the response (saving the Body in case no polling is necessary) + b := &bytes.Buffer{} + err := autorest.Respond(resp, + autorest.ByCopying(b), + autorest.ByUnmarshallingJSON(pt), + autorest.ByClosing()) + resp.Body = ioutil.NopCloser(b) + if err != nil { + return err + } + + // Interpret the results + // -- Terminal states apply regardless + // -- Unknown states are per-service inprogress states + // -- Otherwise, infer state from HTTP status code + if pt.hasTerminated() { + ps.state = pt.state() + } else if pt.state() != "" { + ps.state = operationInProgress + } else { + switch resp.StatusCode { + case http.StatusAccepted: + ps.state = operationInProgress + + case http.StatusNoContent, http.StatusCreated, http.StatusOK: + ps.state = operationSucceeded + + default: + ps.state = operationFailed + } + } + + if ps.state == operationInProgress && ps.uri == "" { + return autorest.NewError("azure", "updatePollingState", "Azure Polling Error - Unable to obtain polling URI for %s %s", resp.Request.Method, resp.Request.URL) + } + + // For failed operation, check for error code and message in + // -- Operation resource + // -- Response + // -- Otherwise, Unknown + if ps.hasFailed() { + if ps.responseFormat == usesOperationResponse { + or := pt.(*operationResource) + ps.code = or.OperationError.Code + ps.message = or.OperationError.Message + } else { + p := pt.(*provisioningStatus) + if p.hasProvisioningError() { + ps.code = p.ProvisioningError.Code + ps.message = p.ProvisioningError.Message + } else { + ps.code = "Unknown" + ps.message = "None" + } + } + } + return nil +} + +func newPollingRequest(resp *http.Response, ps pollingState) (*http.Request, error) { + req := resp.Request + if req == nil { + return nil, autorest.NewError("azure", "newPollingRequest", "Azure Polling Error - Original HTTP request is missing") + } + + reqPoll, err := autorest.Prepare(&http.Request{Cancel: req.Cancel}, + autorest.AsGet(), + autorest.WithBaseURL(ps.uri)) + if err != nil { + return nil, autorest.NewErrorWithError(err, "azure", "newPollingRequest", nil, "Failure creating poll request to %s", ps.uri) + } + + return reqPoll, nil +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/azure.go b/vendor/github.com/Azure/go-autorest/autorest/azure/azure.go new file mode 100644 index 000000000000..75b3aac780f2 --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/azure.go @@ -0,0 +1,165 @@ +/* +Package azure provides Azure-specific implementations used with AutoRest. + +See the included examples for more detail. +*/ +package azure + +import ( + "fmt" + "io/ioutil" + "net/http" + "strconv" + + "github.com/Azure/go-autorest/autorest" +) + +const ( + // HeaderClientID is the Azure extension header to set a user-specified request ID. + HeaderClientID = "x-ms-client-request-id" + + // HeaderReturnClientID is the Azure extension header to set if the user-specified request ID + // should be included in the response. + HeaderReturnClientID = "x-ms-return-client-request-id" + + // HeaderRequestID is the Azure extension header of the service generated request ID returned + // in the response. + HeaderRequestID = "x-ms-request-id" +) + +// ServiceError encapsulates the error response from an Azure service. +type ServiceError struct { + Code string `json:"code"` + Message string `json:"message"` +} + +func (se ServiceError) Error() string { + return fmt.Sprintf("Azure Error: Code=%q Message=%q", se.Code, se.Message) +} + +// RequestError describes an error response returned by Azure service. +type RequestError struct { + autorest.DetailedError + + // The error returned by the Azure service. + ServiceError *ServiceError `json:"error"` + + // The request id (from the x-ms-request-id-header) of the request. + RequestID string +} + +// Error returns a human-friendly error message from service error. +func (e RequestError) Error() string { + return fmt.Sprintf("azure: Service returned an error. Code=%q Message=%q Status=%d", + e.ServiceError.Code, e.ServiceError.Message, e.StatusCode) +} + +// IsAzureError returns true if the passed error is an Azure Service error; false otherwise. +func IsAzureError(e error) bool { + _, ok := e.(*RequestError) + return ok +} + +// NewErrorWithError creates a new Error conforming object from the +// passed packageType, method, statusCode of the given resp (UndefinedStatusCode +// if resp is nil), message, and original error. message is treated as a format +// string to which the optional args apply. +func NewErrorWithError(original error, packageType string, method string, resp *http.Response, message string, args ...interface{}) RequestError { + if v, ok := original.(*RequestError); ok { + return *v + } + + statusCode := autorest.UndefinedStatusCode + if resp != nil { + statusCode = resp.StatusCode + } + return RequestError{ + DetailedError: autorest.DetailedError{ + Original: original, + PackageType: packageType, + Method: method, + StatusCode: statusCode, + Message: fmt.Sprintf(message, args...), + }, + } +} + +// WithReturningClientID returns a PrepareDecorator that adds an HTTP extension header of +// x-ms-client-request-id whose value is the passed, undecorated UUID (e.g., +// "0F39878C-5F76-4DB8-A25D-61D2C193C3CA"). It also sets the x-ms-return-client-request-id +// header to true such that UUID accompanies the http.Response. +func WithReturningClientID(uuid string) autorest.PrepareDecorator { + preparer := autorest.CreatePreparer( + WithClientID(uuid), + WithReturnClientID(true)) + + return func(p autorest.Preparer) autorest.Preparer { + return autorest.PreparerFunc(func(r *http.Request) (*http.Request, error) { + r, err := p.Prepare(r) + if err != nil { + return r, err + } + return preparer.Prepare(r) + }) + } +} + +// WithClientID returns a PrepareDecorator that adds an HTTP extension header of +// x-ms-client-request-id whose value is passed, undecorated UUID (e.g., +// "0F39878C-5F76-4DB8-A25D-61D2C193C3CA"). +func WithClientID(uuid string) autorest.PrepareDecorator { + return autorest.WithHeader(HeaderClientID, uuid) +} + +// WithReturnClientID returns a PrepareDecorator that adds an HTTP extension header of +// x-ms-return-client-request-id whose boolean value indicates if the value of the +// x-ms-client-request-id header should be included in the http.Response. +func WithReturnClientID(b bool) autorest.PrepareDecorator { + return autorest.WithHeader(HeaderReturnClientID, strconv.FormatBool(b)) +} + +// ExtractClientID extracts the client identifier from the x-ms-client-request-id header set on the +// http.Request sent to the service (and returned in the http.Response) +func ExtractClientID(resp *http.Response) string { + return autorest.ExtractHeaderValue(HeaderClientID, resp) +} + +// ExtractRequestID extracts the Azure server generated request identifier from the +// x-ms-request-id header. +func ExtractRequestID(resp *http.Response) string { + return autorest.ExtractHeaderValue(HeaderRequestID, resp) +} + +// WithErrorUnlessStatusCode returns a RespondDecorator that emits an +// azure.RequestError by reading the response body unless the response HTTP status code +// is among the set passed. +// +// If there is a chance service may return responses other than the Azure error +// format and the response cannot be parsed into an error, a decoding error will +// be returned containing the response body. In any case, the Responder will +// return an error if the status code is not satisfied. +// +// If this Responder returns an error, the response body will be replaced with +// an in-memory reader, which needs no further closing. +func WithErrorUnlessStatusCode(codes ...int) autorest.RespondDecorator { + return func(r autorest.Responder) autorest.Responder { + return autorest.ResponderFunc(func(resp *http.Response) error { + err := r.Respond(resp) + if err == nil && !autorest.ResponseHasStatusCode(resp, codes...) { + var e RequestError + defer resp.Body.Close() + + b, decodeErr := autorest.CopyAndDecode(autorest.EncodedAsJSON, resp.Body, &e) + resp.Body = ioutil.NopCloser(&b) // replace body with in-memory reader + if decodeErr != nil || e.ServiceError == nil { + return fmt.Errorf("autorest/azure: error response cannot be parsed: %q error: %v", b.String(), err) + } + + e.RequestID = ExtractRequestID(resp) + e.StatusCode = resp.StatusCode + err = &e + } + return err + }) + } +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/config.go b/vendor/github.com/Azure/go-autorest/autorest/azure/config.go new file mode 100644 index 000000000000..bea30b0d67ea --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/config.go @@ -0,0 +1,13 @@ +package azure + +import ( + "net/url" +) + +// OAuthConfig represents the endpoints needed +// in OAuth operations +type OAuthConfig struct { + AuthorizeEndpoint url.URL + TokenEndpoint url.URL + DeviceCodeEndpoint url.URL +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/devicetoken.go b/vendor/github.com/Azure/go-autorest/autorest/azure/devicetoken.go new file mode 100644 index 000000000000..e1d5498a80f1 --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/devicetoken.go @@ -0,0 +1,193 @@ +package azure + +/* + This file is largely based on rjw57/oauth2device's code, with the follow differences: + * scope -> resource, and only allow a single one + * receive "Message" in the DeviceCode struct and show it to users as the prompt + * azure-xplat-cli has the following behavior that this emulates: + - does not send client_secret during the token exchange + - sends resource again in the token exchange request +*/ + +import ( + "fmt" + "net/http" + "net/url" + "time" + + "github.com/Azure/go-autorest/autorest" +) + +const ( + logPrefix = "autorest/azure/devicetoken:" +) + +var ( + // ErrDeviceGeneric represents an unknown error from the token endpoint when using device flow + ErrDeviceGeneric = fmt.Errorf("%s Error while retrieving OAuth token: Unknown Error", logPrefix) + + // ErrDeviceAccessDenied represents an access denied error from the token endpoint when using device flow + ErrDeviceAccessDenied = fmt.Errorf("%s Error while retrieving OAuth token: Access Denied", logPrefix) + + // ErrDeviceAuthorizationPending represents the server waiting on the user to complete the device flow + ErrDeviceAuthorizationPending = fmt.Errorf("%s Error while retrieving OAuth token: Authorization Pending", logPrefix) + + // ErrDeviceCodeExpired represents the server timing out and expiring the code during device flow + ErrDeviceCodeExpired = fmt.Errorf("%s Error while retrieving OAuth token: Code Expired", logPrefix) + + // ErrDeviceSlowDown represents the service telling us we're polling too often during device flow + ErrDeviceSlowDown = fmt.Errorf("%s Error while retrieving OAuth token: Slow Down", logPrefix) + + errCodeSendingFails = "Error occurred while sending request for Device Authorization Code" + errCodeHandlingFails = "Error occurred while handling response from the Device Endpoint" + errTokenSendingFails = "Error occurred while sending request with device code for a token" + errTokenHandlingFails = "Error occurred while handling response from the Token Endpoint (during device flow)" +) + +// DeviceCode is the object returned by the device auth endpoint +// It contains information to instruct the user to complete the auth flow +type DeviceCode struct { + DeviceCode *string `json:"device_code,omitempty"` + UserCode *string `json:"user_code,omitempty"` + VerificationURL *string `json:"verification_url,omitempty"` + ExpiresIn *int64 `json:"expires_in,string,omitempty"` + Interval *int64 `json:"interval,string,omitempty"` + + Message *string `json:"message"` // Azure specific + Resource string // store the following, stored when initiating, used when exchanging + OAuthConfig OAuthConfig + ClientID string +} + +// TokenError is the object returned by the token exchange endpoint +// when something is amiss +type TokenError struct { + Error *string `json:"error,omitempty"` + ErrorCodes []int `json:"error_codes,omitempty"` + ErrorDescription *string `json:"error_description,omitempty"` + Timestamp *string `json:"timestamp,omitempty"` + TraceID *string `json:"trace_id,omitempty"` +} + +// DeviceToken is the object return by the token exchange endpoint +// It can either look like a Token or an ErrorToken, so put both here +// and check for presence of "Error" to know if we are in error state +type deviceToken struct { + Token + TokenError +} + +// InitiateDeviceAuth initiates a device auth flow. It returns a DeviceCode +// that can be used with CheckForUserCompletion or WaitForUserCompletion. +func InitiateDeviceAuth(client *autorest.Client, oauthConfig OAuthConfig, clientID, resource string) (*DeviceCode, error) { + req, _ := autorest.Prepare( + &http.Request{}, + autorest.AsPost(), + autorest.AsFormURLEncoded(), + autorest.WithBaseURL(oauthConfig.DeviceCodeEndpoint.String()), + autorest.WithFormData(url.Values{ + "client_id": []string{clientID}, + "resource": []string{resource}, + }), + ) + + resp, err := autorest.SendWithSender(client, req) + if err != nil { + return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeSendingFails, err) + } + + var code DeviceCode + err = autorest.Respond( + resp, + autorest.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&code), + autorest.ByClosing()) + if err != nil { + return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, err) + } + + code.ClientID = clientID + code.Resource = resource + code.OAuthConfig = oauthConfig + + return &code, nil +} + +// CheckForUserCompletion takes a DeviceCode and checks with the Azure AD OAuth endpoint +// to see if the device flow has: been completed, timed out, or otherwise failed +func CheckForUserCompletion(client *autorest.Client, code *DeviceCode) (*Token, error) { + req, _ := autorest.Prepare( + &http.Request{}, + autorest.AsPost(), + autorest.AsFormURLEncoded(), + autorest.WithBaseURL(code.OAuthConfig.TokenEndpoint.String()), + autorest.WithFormData(url.Values{ + "client_id": []string{code.ClientID}, + "code": []string{*code.DeviceCode}, + "grant_type": []string{OAuthGrantTypeDeviceCode}, + "resource": []string{code.Resource}, + }), + ) + + resp, err := autorest.SendWithSender(client, req) + if err != nil { + return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenSendingFails, err) + } + + var token deviceToken + err = autorest.Respond( + resp, + autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusBadRequest), + autorest.ByUnmarshallingJSON(&token), + autorest.ByClosing()) + if err != nil { + return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenHandlingFails, err) + } + + if token.Error == nil { + return &token.Token, nil + } + + switch *token.Error { + case "authorization_pending": + return nil, ErrDeviceAuthorizationPending + case "slow_down": + return nil, ErrDeviceSlowDown + case "access_denied": + return nil, ErrDeviceAccessDenied + case "code_expired": + return nil, ErrDeviceCodeExpired + default: + return nil, ErrDeviceGeneric + } +} + +// WaitForUserCompletion calls CheckForUserCompletion repeatedly until a token is granted or an error state occurs. +// This prevents the user from looping and checking against 'ErrDeviceAuthorizationPending'. +func WaitForUserCompletion(client *autorest.Client, code *DeviceCode) (*Token, error) { + intervalDuration := time.Duration(*code.Interval) * time.Second + waitDuration := intervalDuration + + for { + token, err := CheckForUserCompletion(client, code) + + if err == nil { + return token, nil + } + + switch err { + case ErrDeviceSlowDown: + waitDuration += waitDuration + case ErrDeviceAuthorizationPending: + // noop + default: // everything else is "fatal" to us + return nil, err + } + + if waitDuration > (intervalDuration * 3) { + return nil, fmt.Errorf("%s Error waiting for user to complete device flow. Server told us to slow_down too much", logPrefix) + } + + time.Sleep(waitDuration) + } +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go b/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go new file mode 100644 index 000000000000..25e77a319590 --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go @@ -0,0 +1,111 @@ +package azure + +import ( + "fmt" + "net/url" +) + +const ( + activeDirectoryAPIVersion = "1.0" +) + +// Environment represents a set of endpoints for each of Azure's Clouds. +type Environment struct { + Name string + ManagementPortalURL string + PublishSettingsURL string + ServiceManagementEndpoint string + ResourceManagerEndpoint string + ActiveDirectoryEndpoint string + GalleryEndpoint string + KeyVaultEndpoint string + GraphEndpoint string + StorageEndpointSuffix string + SQLDatabaseDNSSuffix string + TrafficManagerDNSSuffix string + KeyVaultDNSSuffix string + ServiceBusEndpointSuffix string +} + +var ( + // PublicCloud is the default public Azure cloud environment + PublicCloud = Environment{ + Name: "AzurePublicCloud", + ManagementPortalURL: "https://manage.windowsazure.com/", + PublishSettingsURL: "https://manage.windowsazure.com/publishsettings/index", + ServiceManagementEndpoint: "https://management.core.windows.net/", + ResourceManagerEndpoint: "https://management.azure.com/", + ActiveDirectoryEndpoint: "https://login.microsoftonline.com/", + GalleryEndpoint: "https://gallery.azure.com/", + KeyVaultEndpoint: "https://vault.azure.net/", + GraphEndpoint: "https://graph.windows.net/", + StorageEndpointSuffix: "core.windows.net", + SQLDatabaseDNSSuffix: "database.windows.net", + TrafficManagerDNSSuffix: "trafficmanager.net", + KeyVaultDNSSuffix: "vault.azure.net", + ServiceBusEndpointSuffix: "servicebus.azure.com", + } + + // USGovernmentCloud is the cloud environment for the US Government + USGovernmentCloud = Environment{ + Name: "AzureUSGovernmentCloud", + ManagementPortalURL: "https://manage.windowsazure.us/", + PublishSettingsURL: "https://manage.windowsazure.us/publishsettings/index", + ServiceManagementEndpoint: "https://management.core.usgovcloudapi.net/", + ResourceManagerEndpoint: "https://management.usgovcloudapi.net", + ActiveDirectoryEndpoint: "https://login.microsoftonline.com/", + GalleryEndpoint: "https://gallery.usgovcloudapi.net/", + KeyVaultEndpoint: "https://vault.azure.net/", + GraphEndpoint: "https://graph.usgovcloudapi.net/", + StorageEndpointSuffix: "core.usgovcloudapi.net", + SQLDatabaseDNSSuffix: "database.usgovcloudapi.net", + TrafficManagerDNSSuffix: "trafficmanager.net", + KeyVaultDNSSuffix: "vault.azure.net", + ServiceBusEndpointSuffix: "servicebus.usgovcloudapi.net", + } + + // ChinaCloud is the cloud environment operated in China + ChinaCloud = Environment{ + Name: "AzureChinaCloud", + ManagementPortalURL: "https://manage.chinacloudapi.com/", + PublishSettingsURL: "https://manage.chinacloudapi.com/publishsettings/index", + ServiceManagementEndpoint: "https://management.core.chinacloudapi.cn/", + ResourceManagerEndpoint: "https://management.chinacloudapi.cn/", + ActiveDirectoryEndpoint: "https://login.chinacloudapi.cn/?api-version=1.0", + GalleryEndpoint: "https://gallery.chinacloudapi.cn/", + KeyVaultEndpoint: "https://vault.azure.net/", + GraphEndpoint: "https://graph.chinacloudapi.cn/", + StorageEndpointSuffix: "core.chinacloudapi.cn", + SQLDatabaseDNSSuffix: "database.chinacloudapi.cn", + TrafficManagerDNSSuffix: "trafficmanager.cn", + KeyVaultDNSSuffix: "vault.azure.net", + ServiceBusEndpointSuffix: "servicebus.chinacloudapi.net", + } +) + +// OAuthConfigForTenant returns an OAuthConfig with tenant specific urls +func (env Environment) OAuthConfigForTenant(tenantID string) (*OAuthConfig, error) { + template := "%s/oauth2/%s?api-version=%s" + u, err := url.Parse(env.ActiveDirectoryEndpoint) + if err != nil { + return nil, err + } + authorizeURL, err := u.Parse(fmt.Sprintf(template, tenantID, "authorize", activeDirectoryAPIVersion)) + if err != nil { + return nil, err + } + tokenURL, err := u.Parse(fmt.Sprintf(template, tenantID, "token", activeDirectoryAPIVersion)) + if err != nil { + return nil, err + } + deviceCodeURL, err := u.Parse(fmt.Sprintf(template, tenantID, "devicecode", activeDirectoryAPIVersion)) + if err != nil { + return nil, err + } + + return &OAuthConfig{ + AuthorizeEndpoint: *authorizeURL, + TokenEndpoint: *tokenURL, + DeviceCodeEndpoint: *deviceCodeURL, + }, nil +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/persist.go b/vendor/github.com/Azure/go-autorest/autorest/azure/persist.go new file mode 100644 index 000000000000..db8bdce48814 --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/persist.go @@ -0,0 +1,58 @@ +package azure + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "os" + "path/filepath" +) + +// LoadToken restores a Token object from a file located at 'path'. +func LoadToken(path string) (*Token, error) { + file, err := os.Open(path) + if err != nil { + return nil, fmt.Errorf("failed to open file (%s) while loading token: %v", path, err) + } + + var token Token + + dec := json.NewDecoder(file) + if err = dec.Decode(&token); err != nil { + return nil, fmt.Errorf("failed to decode contents of file (%s) into Token representation: %v", path, err) + } + return &token, nil +} + +// SaveToken persists an oauth token at the given location on disk. +// It moves the new file into place so it can safely be used to replace an existing file +// that maybe accessed by multiple processes. +func SaveToken(path string, mode os.FileMode, token Token) error { + dir := filepath.Dir(path) + err := os.MkdirAll(dir, os.ModePerm) + if err != nil { + return fmt.Errorf("failed to create directory (%s) to store token in: %v", dir, err) + } + + newFile, err := ioutil.TempFile(dir, "token") + if err != nil { + return fmt.Errorf("failed to create the temp file to write the token: %v", err) + } + tempPath := newFile.Name() + + if err := json.NewEncoder(newFile).Encode(token); err != nil { + return fmt.Errorf("failed to encode token to file (%s) while saving token: %v", tempPath, err) + } + if err := newFile.Close(); err != nil { + return fmt.Errorf("failed to close temp file %s: %v", tempPath, err) + } + + // Atomic replace to avoid multi-writer file corruptions + if err := os.Rename(tempPath, path); err != nil { + return fmt.Errorf("failed to move temporary token to desired output location. src=%s dst=%s: %v", tempPath, path, err) + } + if err := os.Chmod(path, mode); err != nil { + return fmt.Errorf("failed to chmod the token file %s: %v", path, err) + } + return nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/azure/token.go b/vendor/github.com/Azure/go-autorest/autorest/azure/token.go similarity index 62% rename from vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/azure/token.go rename to vendor/github.com/Azure/go-autorest/autorest/azure/token.go index 955b29d8ec57..239fb36a64d4 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/azure/token.go +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/token.go @@ -12,19 +12,22 @@ import ( "strconv" "time" - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go" + "github.com/Azure/go-autorest/autorest" + "github.com/dgrijalva/jwt-go" ) const ( defaultRefresh = 5 * time.Minute - oauthURL = "https://login.microsoftonline.com/{tenantID}/oauth2/{requestType}?api-version=1.0" tokenBaseDate = "1970-01-01T00:00:00Z" - jwtAudienceTemplate = "https://login.microsoftonline.com/%s/oauth2/token" + // OAuthGrantTypeDeviceCode is the "grant_type" identifier used in device flow + OAuthGrantTypeDeviceCode = "device_code" - // AzureResourceManagerScope is the OAuth scope for the Azure Resource Manager. - AzureResourceManagerScope = "https://management.azure.com/" + // OAuthGrantTypeClientCredentials is the "grant_type" identifier used in credential flows + OAuthGrantTypeClientCredentials = "client_credentials" + + // OAuthGrantTypeRefreshToken is the "grant_type" identifier used in refresh token flows + OAuthGrantTypeRefreshToken = "refresh_token" ) var expirationBase time.Time @@ -33,9 +36,14 @@ func init() { expirationBase, _ = time.Parse(time.RFC3339, tokenBaseDate) } +// TokenRefreshCallback is the type representing callbacks that will be called after +// a successful token refresh +type TokenRefreshCallback func(Token) error + // Token encapsulates the access token used to authorize Azure requests. type Token struct { - AccessToken string `json:"access_token"` + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token"` ExpiresIn string `json:"expires_in"` ExpiresOn string `json:"expires_on"` @@ -75,6 +83,17 @@ func (t *Token) WithAuthorization() autorest.PrepareDecorator { } } +// ServicePrincipalNoSecret represents a secret type that contains no secret +// meaning it is not valid for fetching a fresh token. This is used by Manual +type ServicePrincipalNoSecret struct { +} + +// SetAuthenticationValues is a method of the interface ServicePrincipalSecret +// It only returns an error for the ServicePrincipalNoSecret type +func (noSecret *ServicePrincipalNoSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { + return fmt.Errorf("Manually created ServicePrincipalToken does not contain secret material to retrieve a new access token.") +} + // ServicePrincipalSecret is an interface that allows various secret mechanism to fill the form // that is submitted when acquiring an oAuth token. type ServicePrincipalSecret interface { @@ -86,7 +105,7 @@ type ServicePrincipalTokenSecret struct { ClientSecret string } -// SetAuthenticationValues is a method of the interface ServicePrincipalTokenSecret. +// SetAuthenticationValues is a method of the interface ServicePrincipalSecret. // It will populate the form submitted during oAuth Token Acquisition using the client_secret. func (tokenSecret *ServicePrincipalTokenSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { v.Set("client_secret", tokenSecret.ClientSecret) @@ -119,7 +138,7 @@ func (secret *ServicePrincipalCertificateSecret) SignJwt(spt *ServicePrincipalTo token := jwt.New(jwt.SigningMethodRS256) token.Header["x5t"] = thumbprint token.Claims = map[string]interface{}{ - "aud": fmt.Sprintf(jwtAudienceTemplate, spt.tenantID), + "aud": spt.oauthConfig.TokenEndpoint, "iss": spt.clientID, "sub": spt.clientID, "jti": base64.URLEncoding.EncodeToString(jti), @@ -131,7 +150,7 @@ func (secret *ServicePrincipalCertificateSecret) SignJwt(spt *ServicePrincipalTo return signedString, nil } -// SetAuthenticationValues is a method of the interface ServicePrincipalTokenSecret. +// SetAuthenticationValues is a method of the interface ServicePrincipalSecret. // It will populate the form submitted during oAuth Token Acquisition using a JWT signed with a certificate. func (secret *ServicePrincipalCertificateSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { jwt, err := secret.SignJwt(spt) @@ -149,51 +168,73 @@ type ServicePrincipalToken struct { Token secret ServicePrincipalSecret + oauthConfig OAuthConfig clientID string - tenantID string resource string autoRefresh bool refreshWithin time.Duration sender autorest.Sender + + refreshCallbacks []TokenRefreshCallback } // NewServicePrincipalTokenWithSecret create a ServicePrincipalToken using the supplied ServicePrincipalSecret implementation. -func NewServicePrincipalTokenWithSecret(id string, tenantID string, resource string, secret ServicePrincipalSecret) (*ServicePrincipalToken, error) { +func NewServicePrincipalTokenWithSecret(oauthConfig OAuthConfig, id string, resource string, secret ServicePrincipalSecret, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { spt := &ServicePrincipalToken{ - secret: secret, - clientID: id, - resource: resource, - tenantID: tenantID, - autoRefresh: true, - refreshWithin: defaultRefresh, - sender: &http.Client{}, + oauthConfig: oauthConfig, + secret: secret, + clientID: id, + resource: resource, + autoRefresh: true, + refreshWithin: defaultRefresh, + sender: &http.Client{}, + refreshCallbacks: callbacks, + } + return spt, nil +} + +// NewServicePrincipalTokenFromManualToken creates a ServicePrincipalToken using the supplied token +func NewServicePrincipalTokenFromManualToken(oauthConfig OAuthConfig, clientID string, resource string, token Token, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { + spt, err := NewServicePrincipalTokenWithSecret( + oauthConfig, + clientID, + resource, + &ServicePrincipalNoSecret{}, + callbacks...) + if err != nil { + return nil, err } + + spt.Token = token + return spt, nil } // NewServicePrincipalToken creates a ServicePrincipalToken from the supplied Service Principal // credentials scoped to the named resource. -func NewServicePrincipalToken(id string, secret string, tenantID string, resource string) (*ServicePrincipalToken, error) { +func NewServicePrincipalToken(oauthConfig OAuthConfig, clientID string, secret string, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { return NewServicePrincipalTokenWithSecret( - id, - tenantID, + oauthConfig, + clientID, resource, &ServicePrincipalTokenSecret{ ClientSecret: secret, }, + callbacks..., ) } // NewServicePrincipalTokenFromCertificate create a ServicePrincipalToken from the supplied pkcs12 bytes. -func NewServicePrincipalTokenFromCertificate(id string, certificate *x509.Certificate, privateKey *rsa.PrivateKey, tenantID string, resource string) (*ServicePrincipalToken, error) { +func NewServicePrincipalTokenFromCertificate(oauthConfig OAuthConfig, clientID string, certificate *x509.Certificate, privateKey *rsa.PrivateKey, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { return NewServicePrincipalTokenWithSecret( - id, - tenantID, + oauthConfig, + clientID, resource, &ServicePrincipalCertificateSecret{ PrivateKey: privateKey, Certificate: certificate, }, + callbacks..., ) } @@ -206,54 +247,78 @@ func (spt *ServicePrincipalToken) EnsureFresh() error { return nil } +// InvokeRefreshCallbacks calls any TokenRefreshCallbacks that were added to the SPT during initialization +func (spt *ServicePrincipalToken) InvokeRefreshCallbacks(token Token) error { + if spt.refreshCallbacks != nil { + for _, callback := range spt.refreshCallbacks { + err := callback(spt.Token) + if err != nil { + return autorest.NewErrorWithError(err, + "azure.ServicePrincipalToken", "InvokeRefreshCallbacks", nil, "A TokenRefreshCallback handler returned an error") + } + } + } + return nil +} + // Refresh obtains a fresh token for the Service Principal. func (spt *ServicePrincipalToken) Refresh() error { - p := map[string]interface{}{ - "tenantID": spt.tenantID, - "requestType": "token", - } + return spt.refreshInternal(spt.resource) +} +// RefreshExchange refreshes the token, but for a different resource. +func (spt *ServicePrincipalToken) RefreshExchange(resource string) error { + return spt.refreshInternal(resource) +} + +func (spt *ServicePrincipalToken) refreshInternal(resource string) error { v := url.Values{} v.Set("client_id", spt.clientID) - v.Set("grant_type", "client_credentials") - v.Set("resource", spt.resource) - - err := spt.secret.SetAuthenticationValues(spt, &v) - if err != nil { - return err + v.Set("resource", resource) + + if spt.RefreshToken != "" { + v.Set("grant_type", OAuthGrantTypeRefreshToken) + v.Set("refresh_token", spt.RefreshToken) + } else { + v.Set("grant_type", OAuthGrantTypeClientCredentials) + err := spt.secret.SetAuthenticationValues(spt, &v) + if err != nil { + return err + } } - req, err := autorest.Prepare(&http.Request{}, + req, _ := autorest.Prepare(&http.Request{}, autorest.AsPost(), autorest.AsFormURLEncoded(), - autorest.WithBaseURL(oauthURL), - autorest.WithPathParameters(p), + autorest.WithBaseURL(spt.oauthConfig.TokenEndpoint.String()), autorest.WithFormData(v)) - if err != nil { - return err - } resp, err := autorest.SendWithSender(spt.sender, req) if err != nil { return autorest.NewErrorWithError(err, - "azure.ServicePrincipalToken", "Refresh", resp.StatusCode, "Failure sending request for Service Principal %s", + "azure.ServicePrincipalToken", "Refresh", resp, "Failure sending request for Service Principal %s", spt.clientID) } var newToken Token - err = autorest.Respond(resp, autorest.WithErrorUnlessOK(), autorest.ByUnmarshallingJSON(&newToken), autorest.ByClosing()) if err != nil { return autorest.NewErrorWithError(err, - "azure.ServicePrincipalToken", "Refresh", resp.StatusCode, "Failure handling response to Service Principal %s request", + "azure.ServicePrincipalToken", "Refresh", resp, "Failure handling response to Service Principal %s request", spt.clientID) } spt.Token = newToken + err = spt.InvokeRefreshCallbacks(newToken) + if err != nil { + // its already wrapped inside InvokeRefreshCallbacks + return err + } + return nil } @@ -288,7 +353,7 @@ func (spt *ServicePrincipalToken) WithAuthorization() autorest.PrepareDecorator err := spt.EnsureFresh() if err != nil { return r, autorest.NewErrorWithError(err, - "azure.ServicePrincipalToken", "WithAuthorization", autorest.UndefinedStatusCode, "Failed to refresh Service Principal Token for request to %s", + "azure.ServicePrincipalToken", "WithAuthorization", nil, "Failed to refresh Service Principal Token for request to %s", r.URL) } } diff --git a/vendor/github.com/Azure/go-autorest/autorest/client.go b/vendor/github.com/Azure/go-autorest/autorest/client.go new file mode 100644 index 000000000000..ce156f74fd14 --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/client.go @@ -0,0 +1,190 @@ +package autorest + +import ( + "bytes" + "fmt" + "io" + "io/ioutil" + "log" + "net/http" + "time" +) + +const ( + // DefaultPollingDelay is a reasonable delay between polling requests. + DefaultPollingDelay = 60 * time.Second + + // DefaultPollingDuration is a reasonable total polling duration. + DefaultPollingDuration = 15 * time.Minute +) + +const ( + requestFormat = `HTTP Request Begin =================================================== +%s +===================================================== HTTP Request End +` + responseFormat = `HTTP Response Begin =================================================== +%s +===================================================== HTTP Response End +` +) + +// Response serves as the base for all responses from generated clients. It provides access to the +// last http.Response. +type Response struct { + *http.Response `json:"-"` +} + +// LoggingInspector implements request and response inspectors that log the full request and +// response to a supplied log. +type LoggingInspector struct { + Logger *log.Logger +} + +// WithInspection returns a PrepareDecorator that emits the http.Request to the supplied logger. The +// body is restored after being emitted. +// +// Note: Since it reads the entire Body, this decorator should not be used where body streaming is +// important. It is best used to trace JSON or similar body values. +func (li LoggingInspector) WithInspection() PrepareDecorator { + return func(p Preparer) Preparer { + return PreparerFunc(func(r *http.Request) (*http.Request, error) { + var body, b bytes.Buffer + + defer r.Body.Close() + + r.Body = ioutil.NopCloser(io.TeeReader(r.Body, &body)) + if err := r.Write(&b); err != nil { + return nil, fmt.Errorf("Failed to write response: %v", err) + } + + li.Logger.Printf(requestFormat, b.String()) + + r.Body = ioutil.NopCloser(&body) + return p.Prepare(r) + }) + } +} + +// ByInspecting returns a RespondDecorator that emits the http.Response to the supplied logger. The +// body is restored after being emitted. +// +// Note: Since it reads the entire Body, this decorator should not be used where body streaming is +// important. It is best used to trace JSON or similar body values. +func (li LoggingInspector) ByInspecting() RespondDecorator { + return func(r Responder) Responder { + return ResponderFunc(func(resp *http.Response) error { + var body, b bytes.Buffer + + defer resp.Body.Close() + + resp.Body = ioutil.NopCloser(io.TeeReader(resp.Body, &body)) + if err := resp.Write(&b); err != nil { + return fmt.Errorf("Failed to write response: %v", err) + } + + li.Logger.Printf(responseFormat, b.String()) + + resp.Body = ioutil.NopCloser(&body) + return r.Respond(resp) + }) + } +} + +// Client is the base for autorest generated clients. It provides default, "do nothing" +// implementations of an Authorizer, RequestInspector, and ResponseInspector. It also returns the +// standard, undecorated http.Client as a default Sender. +// +// Generated clients should also use Error (see NewError and NewErrorWithError) for errors and +// return responses that compose with Response. +// +// Most customization of generated clients is best achieved by supplying a custom Authorizer, custom +// RequestInspector, and / or custom ResponseInspector. Users may log requests, implement circuit +// breakers (see https://msdn.microsoft.com/en-us/library/dn589784.aspx) or otherwise influence +// sending the request by providing a decorated Sender. +type Client struct { + Authorizer Authorizer + Sender Sender + RequestInspector PrepareDecorator + ResponseInspector RespondDecorator + + // PollingDelay sets the polling frequency used in absence of a Retry-After HTTP header + PollingDelay time.Duration + + // PollingDuration sets the maximum polling time after which an error is returned. + PollingDuration time.Duration + + // UserAgent, if not empty, will be set as the HTTP User-Agent header on all requests sent + // through the Do method. + UserAgent string +} + +// NewClientWithUserAgent returns an instance of a Client with the UserAgent set to the passed +// string. +func NewClientWithUserAgent(ua string) Client { + c := Client{PollingDelay: DefaultPollingDelay, PollingDuration: DefaultPollingDuration} + c.UserAgent = ua + return c +} + +// Do implements the Sender interface by invoking the active Sender after applying authorization. +// If Sender is not set, it uses a new instance of http.Client. In both cases it will, if UserAgent +// is set, apply set the User-Agent header. +func (c Client) Do(r *http.Request) (*http.Response, error) { + if r.UserAgent() == "" { + r, _ = Prepare(r, + WithUserAgent(c.UserAgent)) + } + r, err := Prepare(r, + c.WithInspection(), + c.WithAuthorization()) + if err != nil { + return nil, NewErrorWithError(err, "autorest/Client", "Do", nil, "Preparing request failed") + } + + resp, err := c.sender().Do(r) + Respond(resp, + c.ByInspecting()) + + return resp, err +} + +// sender returns the Sender to which to send requests. +func (c Client) sender() Sender { + if c.Sender == nil { + return http.DefaultClient + } + return c.Sender +} + +// WithAuthorization is a convenience method that returns the WithAuthorization PrepareDecorator +// from the current Authorizer. If not Authorizer is set, it uses the NullAuthorizer. +func (c Client) WithAuthorization() PrepareDecorator { + return c.authorizer().WithAuthorization() +} + +// authorizer returns the Authorizer to use. +func (c Client) authorizer() Authorizer { + if c.Authorizer == nil { + return NullAuthorizer{} + } + return c.Authorizer +} + +// WithInspection is a convenience method that passes the request to the supplied RequestInspector, +// if present, or returns the WithNothing PrepareDecorator otherwise. +func (c Client) WithInspection() PrepareDecorator { + if c.RequestInspector == nil { + return WithNothing() + } + return c.RequestInspector +} + +// ByInspecting is a convenience method that passes the response to the supplied ResponseInspector, +// if present, or returns the ByIgnoring RespondDecorator otherwise. +func (c Client) ByInspecting() RespondDecorator { + if c.ResponseInspector == nil { + return ByIgnoring() + } + return c.ResponseInspector +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/date/date.go b/vendor/github.com/Azure/go-autorest/autorest/date/date.go similarity index 82% rename from vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/date/date.go rename to vendor/github.com/Azure/go-autorest/autorest/date/date.go index c0514bc20635..80ca60e9b08a 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/date/date.go +++ b/vendor/github.com/Azure/go-autorest/autorest/date/date.go @@ -11,9 +11,10 @@ import ( ) const ( - rfc3339FullDate = "2006-01-02" - dateFormat = "%4d-%02d-%02d" - jsonFormat = `"%4d-%02d-%02d"` + fullDate = "2006-01-02" + fullDateJSON = `"2006-01-02"` + dateFormat = "%04d-%02d-%02d" + jsonFormat = `"%04d-%02d-%02d"` ) // Date defines a type similar to time.Time but assumes a layout of RFC3339 full-date (i.e., @@ -24,9 +25,12 @@ type Date struct { // ParseDate create a new Date from the passed string. func ParseDate(date string) (d Date, err error) { - d = Date{} - d.Time, err = time.Parse(rfc3339FullDate, date) - return d, err + return parseDate(date, fullDate) +} + +func parseDate(date string, format string) (Date, error) { + d, err := time.Parse(format, date) + return Date{Time: d}, err } // MarshalBinary preserves the Date as a byte array conforming to RFC3339 full-date (i.e., @@ -50,14 +54,8 @@ func (d Date) MarshalJSON() (json []byte, err error) { // UnmarshalJSON reconstitutes the Date from a JSON string conforming to RFC3339 full-date (i.e., // 2006-01-02). func (d *Date) UnmarshalJSON(data []byte) (err error) { - if data[0] == '"' { - data = data[1 : len(data)-1] - } - d.Time, err = time.Parse(rfc3339FullDate, string(data)) - if err != nil { - return err - } - return nil + d.Time, err = time.Parse(fullDateJSON, string(data)) + return err } // MarshalText preserves the Date as a byte array conforming to RFC3339 full-date (i.e., @@ -69,11 +67,8 @@ func (d Date) MarshalText() (text []byte, err error) { // UnmarshalText reconstitutes a Date saved as a byte array conforming to RFC3339 full-date (i.e., // 2006-01-02). func (d *Date) UnmarshalText(data []byte) (err error) { - d.Time, err = time.Parse(rfc3339FullDate, string(data)) - if err != nil { - return err - } - return nil + d.Time, err = time.Parse(fullDate, string(data)) + return err } // String returns the Date formatted as an RFC3339 full-date string (i.e., 2006-01-02). diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/date/time.go b/vendor/github.com/Azure/go-autorest/autorest/date/time.go similarity index 60% rename from vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/date/time.go rename to vendor/github.com/Azure/go-autorest/autorest/date/time.go index ccac424c1756..fd3c5854e79d 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/date/time.go +++ b/vendor/github.com/Azure/go-autorest/autorest/date/time.go @@ -4,60 +4,60 @@ import ( "time" ) +const ( + rfc3339JSON = `"` + time.RFC3339Nano + `"` + rfc3339 = time.RFC3339Nano +) + // Time defines a type similar to time.Time but assumes a layout of RFC3339 date-time (i.e., // 2006-01-02T15:04:05Z). type Time struct { time.Time } -// ParseTime creates a new Time from the passed string. -func ParseTime(date string) (d Time, err error) { - d = Time{} - d.Time, err = time.Parse(time.RFC3339, date) - return d, err -} - // MarshalBinary preserves the Time as a byte array conforming to RFC3339 date-time (i.e., // 2006-01-02T15:04:05Z). -func (d Time) MarshalBinary() ([]byte, error) { - return d.Time.MarshalText() +func (t Time) MarshalBinary() ([]byte, error) { + return t.Time.MarshalText() } // UnmarshalBinary reconstitutes a Time saved as a byte array conforming to RFC3339 date-time // (i.e., 2006-01-02T15:04:05Z). -func (d *Time) UnmarshalBinary(data []byte) error { - return d.Time.UnmarshalText(data) +func (t *Time) UnmarshalBinary(data []byte) error { + return t.UnmarshalText(data) } // MarshalJSON preserves the Time as a JSON string conforming to RFC3339 date-time (i.e., // 2006-01-02T15:04:05Z). -func (d Time) MarshalJSON() (json []byte, err error) { - return d.Time.MarshalJSON() +func (t Time) MarshalJSON() (json []byte, err error) { + return t.Time.MarshalJSON() } // UnmarshalJSON reconstitutes the Time from a JSON string conforming to RFC3339 date-time // (i.e., 2006-01-02T15:04:05Z). -func (d *Time) UnmarshalJSON(data []byte) (err error) { - return d.Time.UnmarshalJSON(data) +func (t *Time) UnmarshalJSON(data []byte) (err error) { + t.Time, err = ParseTime(rfc3339JSON, string(data)) + return err } // MarshalText preserves the Time as a byte array conforming to RFC3339 date-time (i.e., // 2006-01-02T15:04:05Z). -func (d Time) MarshalText() (text []byte, err error) { - return d.Time.MarshalText() +func (t Time) MarshalText() (text []byte, err error) { + return t.Time.MarshalText() } // UnmarshalText reconstitutes a Time saved as a byte array conforming to RFC3339 date-time // (i.e., 2006-01-02T15:04:05Z). -func (d *Time) UnmarshalText(data []byte) (err error) { - return d.Time.UnmarshalText(data) +func (t *Time) UnmarshalText(data []byte) (err error) { + t.Time, err = ParseTime(rfc3339, string(data)) + return err } // String returns the Time formatted as an RFC3339 date-time string (i.e., // 2006-01-02T15:04:05Z). -func (d Time) String() string { +func (t Time) String() string { // Note: time.Time.String does not return an RFC3339 compliant string, time.Time.MarshalText does. - b, err := d.Time.MarshalText() + b, err := t.MarshalText() if err != nil { return "" } @@ -65,6 +65,6 @@ func (d Time) String() string { } // ToTime returns a Time as a time.Time -func (d Time) ToTime() time.Time { - return d.Time +func (t Time) ToTime() time.Time { + return t.Time } diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/timerfc1123.go b/vendor/github.com/Azure/go-autorest/autorest/date/timerfc1123.go new file mode 100644 index 000000000000..11995fb9f2c5 --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/date/timerfc1123.go @@ -0,0 +1,86 @@ +package date + +import ( + "errors" + "time" +) + +const ( + rfc1123JSON = `"` + time.RFC1123 + `"` + rfc1123 = time.RFC1123 +) + +// TimeRFC1123 defines a type similar to time.Time but assumes a layout of RFC1123 date-time (i.e., +// Mon, 02 Jan 2006 15:04:05 MST). +type TimeRFC1123 struct { + time.Time +} + +// UnmarshalJSON reconstitutes the Time from a JSON string conforming to RFC1123 date-time +// (i.e., Mon, 02 Jan 2006 15:04:05 MST). +func (t *TimeRFC1123) UnmarshalJSON(data []byte) (err error) { + t.Time, err = ParseTime(rfc1123JSON, string(data)) + if err != nil { + return err + } + return nil +} + +// MarshalJSON preserves the Time as a JSON string conforming to RFC1123 date-time (i.e., +// Mon, 02 Jan 2006 15:04:05 MST). +func (t TimeRFC1123) MarshalJSON() ([]byte, error) { + if y := t.Year(); y < 0 || y >= 10000 { + return nil, errors.New("Time.MarshalJSON: year outside of range [0,9999]") + } + b := []byte(t.Format(rfc1123JSON)) + return b, nil +} + +// MarshalText preserves the Time as a byte array conforming to RFC1123 date-time (i.e., +// Mon, 02 Jan 2006 15:04:05 MST). +func (t TimeRFC1123) MarshalText() ([]byte, error) { + if y := t.Year(); y < 0 || y >= 10000 { + return nil, errors.New("Time.MarshalText: year outside of range [0,9999]") + } + + b := []byte(t.Format(rfc1123)) + return b, nil +} + +// UnmarshalText reconstitutes a Time saved as a byte array conforming to RFC1123 date-time +// (i.e., Mon, 02 Jan 2006 15:04:05 MST). +func (t *TimeRFC1123) UnmarshalText(data []byte) (err error) { + t.Time, err = ParseTime(rfc1123, string(data)) + if err != nil { + return err + } + return nil +} + +// MarshalBinary preserves the Time as a byte array conforming to RFC1123 date-time (i.e., +// Mon, 02 Jan 2006 15:04:05 MST). +func (t TimeRFC1123) MarshalBinary() ([]byte, error) { + return t.MarshalText() +} + +// UnmarshalBinary reconstitutes a Time saved as a byte array conforming to RFC1123 date-time +// (i.e., Mon, 02 Jan 2006 15:04:05 MST). +func (t *TimeRFC1123) UnmarshalBinary(data []byte) error { + return t.UnmarshalText(data) +} + +// ToTime returns a Time as a time.Time +func (t TimeRFC1123) ToTime() time.Time { + return t.Time +} + +// String returns the Time formatted as an RFC1123 date-time string (i.e., +// Mon, 02 Jan 2006 15:04:05 MST). +func (t TimeRFC1123) String() string { + // Note: time.Time.String does not return an RFC1123 compliant string, time.Time.MarshalText does. + b, err := t.MarshalText() + if err != nil { + return "" + } + return string(b) +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/utility.go b/vendor/github.com/Azure/go-autorest/autorest/date/utility.go new file mode 100644 index 000000000000..207b1a240a3a --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/date/utility.go @@ -0,0 +1,11 @@ +package date + +import ( + "strings" + "time" +) + +// ParseTime to parse Time string to specified format. +func ParseTime(format string, t string) (d time.Time, err error) { + return time.Parse(format, strings.ToUpper(t)) +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/error.go b/vendor/github.com/Azure/go-autorest/autorest/error.go new file mode 100644 index 000000000000..da49b12cb0d6 --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/error.go @@ -0,0 +1,77 @@ +package autorest + +import ( + "fmt" + "net/http" +) + +const ( + // UndefinedStatusCode is used when HTTP status code is not available for an error. + UndefinedStatusCode = 0 +) + +// DetailedError encloses a error with details of the package, method, and associated HTTP +// status code (if any). +type DetailedError struct { + Original error + + // PackageType is the package type of the object emitting the error. For types, the value + // matches that produced the the '%T' format specifier of the fmt package. For other elements, + // such as functions, it is just the package name (e.g., "autorest"). + PackageType string + + // Method is the name of the method raising the error. + Method string + + // StatusCode is the HTTP Response StatusCode (if non-zero) that led to the error. + StatusCode int + + // Message is the error message. + Message string +} + +// NewError creates a new Error conforming object from the passed packageType, method, and +// message. message is treated as a format string to which the optional args apply. +func NewError(packageType string, method string, message string, args ...interface{}) DetailedError { + return NewErrorWithError(nil, packageType, method, nil, message, args...) +} + +// NewErrorWithResponse creates a new Error conforming object from the passed +// packageType, method, statusCode of the given resp (UndefinedStatusCode if +// resp is nil), and message. message is treated as a format string to which the +// optional args apply. +func NewErrorWithResponse(packageType string, method string, resp *http.Response, message string, args ...interface{}) DetailedError { + return NewErrorWithError(nil, packageType, method, resp, message, args...) +} + +// NewErrorWithError creates a new Error conforming object from the +// passed packageType, method, statusCode of the given resp (UndefinedStatusCode +// if resp is nil), message, and original error. message is treated as a format +// string to which the optional args apply. +func NewErrorWithError(original error, packageType string, method string, resp *http.Response, message string, args ...interface{}) DetailedError { + if v, ok := original.(DetailedError); ok { + return v + } + + statusCode := UndefinedStatusCode + if resp != nil { + statusCode = resp.StatusCode + } + + return DetailedError{ + Original: original, + PackageType: packageType, + Method: method, + StatusCode: statusCode, + Message: fmt.Sprintf(message, args...), + } +} + +// Error returns a formatted containing all available details (i.e., PackageType, Method, +// StatusCode, Message, and original error (if any)). +func (e DetailedError) Error() string { + if e.Original == nil { + return fmt.Sprintf("%s#%s: %s: StatusCode=%d", e.PackageType, e.Method, e.Message, e.StatusCode) + } + return fmt.Sprintf("%s#%s: %s: StatusCode=%d -- Original Error: %v", e.PackageType, e.Method, e.Message, e.StatusCode, e.Original) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/preparer.go b/vendor/github.com/Azure/go-autorest/autorest/preparer.go similarity index 86% rename from vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/preparer.go rename to vendor/github.com/Azure/go-autorest/autorest/preparer.go index d02b1c84d594..c0735f07fe8b 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/preparer.go +++ b/vendor/github.com/Azure/go-autorest/autorest/preparer.go @@ -165,7 +165,11 @@ func WithBaseURL(baseURL string) PrepareDecorator { return PreparerFunc(func(r *http.Request) (*http.Request, error) { r, err := p.Prepare(r) if err == nil { - u, err := url.Parse(baseURL) + var u *url.URL + u, err = url.Parse(baseURL) + if u.Scheme == "" { + err = fmt.Errorf("autorest: No scheme detected in URL %s", baseURL) + } if err == nil { r.URL = u } @@ -191,6 +195,51 @@ func WithFormData(v url.Values) PrepareDecorator { } } +// WithBool returns a PrepareDecorator that encodes the passed bool into the body of the request +// and sets the Content-Length header. +func WithBool(v bool) PrepareDecorator { + return WithString(fmt.Sprintf("%v", v)) +} + +// WithFloat32 returns a PrepareDecorator that encodes the passed float32 into the body of the +// request and sets the Content-Length header. +func WithFloat32(v float32) PrepareDecorator { + return WithString(fmt.Sprintf("%v", v)) +} + +// WithFloat64 returns a PrepareDecorator that encodes the passed float64 into the body of the +// request and sets the Content-Length header. +func WithFloat64(v float64) PrepareDecorator { + return WithString(fmt.Sprintf("%v", v)) +} + +// WithInt32 returns a PrepareDecorator that encodes the passed int32 into the body of the request +// and sets the Content-Length header. +func WithInt32(v int32) PrepareDecorator { + return WithString(fmt.Sprintf("%v", v)) +} + +// WithInt64 returns a PrepareDecorator that encodes the passed int64 into the body of the request +// and sets the Content-Length header. +func WithInt64(v int64) PrepareDecorator { + return WithString(fmt.Sprintf("%v", v)) +} + +// WithString returns a PrepareDecorator that encodes the passed string into the body of the request +// and sets the Content-Length header. +func WithString(v string) PrepareDecorator { + return func(p Preparer) Preparer { + return PreparerFunc(func(r *http.Request) (*http.Request, error) { + r, err := p.Prepare(r) + if err == nil { + r.ContentLength = int64(len(v)) + r.Body = ioutil.NopCloser(strings.NewReader(v)) + } + return r, err + }) + } +} + // WithJSON returns a PrepareDecorator that encodes the data passed as JSON into the body of the // request and sets the Content-Length header. func WithJSON(v interface{}) PrepareDecorator { diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/responder.go b/vendor/github.com/Azure/go-autorest/autorest/responder.go similarity index 76% rename from vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/responder.go rename to vendor/github.com/Azure/go-autorest/autorest/responder.go index 8b14eb41cfd8..e377ad48afef 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/responder.go +++ b/vendor/github.com/Azure/go-autorest/autorest/responder.go @@ -1,8 +1,13 @@ package autorest import ( + "bytes" + "encoding/json" + "encoding/xml" "fmt" + "io/ioutil" "net/http" + "strings" ) // Responder is the interface that wraps the Respond method. @@ -68,6 +73,20 @@ func ByIgnoring() RespondDecorator { } } +// ByCopying copies the contents of the http.Response Body into the passed bytes.Buffer as +// the Body is read. +func ByCopying(b *bytes.Buffer) RespondDecorator { + return func(r Responder) Responder { + return ResponderFunc(func(resp *http.Response) error { + err := r.Respond(resp) + if err == nil && resp != nil && resp.Body != nil { + resp.Body = TeeReadCloser(resp.Body, b) + } + return err + }) + } +} + // ByClosing returns a RespondDecorator that first invokes the passed Responder after which it // closes the response body. Since the passed Responder is invoked prior to closing the response // body, the decorator may occur anywhere within the set. @@ -76,7 +95,9 @@ func ByClosing() RespondDecorator { return ResponderFunc(func(resp *http.Response) error { err := r.Respond(resp) if resp != nil && resp.Body != nil { - resp.Body.Close() + if err := resp.Body.Close(); err != nil { + return fmt.Errorf("Error closing the response body: %v", err) + } } return err }) @@ -90,7 +111,9 @@ func ByClosingIfError() RespondDecorator { return ResponderFunc(func(resp *http.Response) error { err := r.Respond(resp) if err != nil && resp != nil && resp.Body != nil { - resp.Body.Close() + if err := resp.Body.Close(); err != nil { + return fmt.Errorf("Error closing the response body: %v", err) + } } return err }) @@ -100,29 +123,45 @@ func ByClosingIfError() RespondDecorator { // ByUnmarshallingJSON returns a RespondDecorator that decodes a JSON document returned in the // response Body into the value pointed to by v. func ByUnmarshallingJSON(v interface{}) RespondDecorator { - return byUnmarshallingAs(EncodedAsJSON, v) + return func(r Responder) Responder { + return ResponderFunc(func(resp *http.Response) error { + err := r.Respond(resp) + if err == nil { + b, errInner := ioutil.ReadAll(resp.Body) + if errInner != nil { + err = fmt.Errorf("Error occurred reading http.Response#Body - Error = '%v'", errInner) + } else if len(strings.Trim(string(b), " ")) > 0 { + errInner = json.Unmarshal(b, v) + if errInner != nil { + err = fmt.Errorf("Error occurred unmarshalling JSON - Error = '%v' JSON = '%s'", errInner, string(b)) + } + } + } + return err + }) + } } // ByUnmarshallingXML returns a RespondDecorator that decodes a XML document returned in the // response Body into the value pointed to by v. func ByUnmarshallingXML(v interface{}) RespondDecorator { - return byUnmarshallingAs(EncodedAsXML, v) -} - -func byUnmarshallingAs(encodedAs EncodedAs, v interface{}) RespondDecorator { return func(r Responder) Responder { return ResponderFunc(func(resp *http.Response) error { err := r.Respond(resp) if err == nil { - b, errDecode := CopyAndDecode(encodedAs, resp.Body, v) - if errDecode != nil { - err = fmt.Errorf("Error (%v) occurred decoding %s (\"%s\")", errDecode, encodedAs, b.String()) + b, errInner := ioutil.ReadAll(resp.Body) + if errInner != nil { + err = fmt.Errorf("Error occurred reading http.Response#Body - Error = '%v'", errInner) + } else { + errInner = xml.Unmarshal(b, v) + if errInner != nil { + err = fmt.Errorf("Error occurred unmarshalling Xml - Error = '%v' Xml = '%s'", errInner, string(b)) + } } } return err }) } - } // WithErrorUnlessStatusCode returns a RespondDecorator that emits an error unless the response @@ -133,7 +172,7 @@ func WithErrorUnlessStatusCode(codes ...int) RespondDecorator { return ResponderFunc(func(resp *http.Response) error { err := r.Respond(resp) if err == nil && !ResponseHasStatusCode(resp, codes...) { - err = NewErrorWithStatusCode("autorest", "WithErrorUnlessStatusCode", resp.StatusCode, "%v %v failed with %s", + err = NewErrorWithResponse("autorest", "WithErrorUnlessStatusCode", resp, "%v %v failed with %s", resp.Request.Method, resp.Request.URL, resp.Status) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/sender.go b/vendor/github.com/Azure/go-autorest/autorest/sender.go similarity index 70% rename from vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/sender.go rename to vendor/github.com/Azure/go-autorest/autorest/sender.go index 6d6d8f011063..b646a4832210 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/sender.go +++ b/vendor/github.com/Azure/go-autorest/autorest/sender.go @@ -1,6 +1,7 @@ package autorest import ( + "fmt" "log" "math" "net/http" @@ -65,32 +66,15 @@ func SendWithSender(s Sender, r *http.Request, decorators ...SendDecorator) (*ht } // AfterDelay returns a SendDecorator that delays for the passed time.Duration before -// invoking the Sender. +// invoking the Sender. The delay may be terminated by closing the optional channel on the +// http.Request. If canceled, no further Senders are invoked. func AfterDelay(d time.Duration) SendDecorator { return func(s Sender) Sender { return SenderFunc(func(r *http.Request) (*http.Response, error) { - time.Sleep(d) - return s.Do(r) - }) - } -} - -// AfterRetryDelay returns a SendDecorator that delays for the number of seconds specified in the -// Retry-After header of the prior response when polling is required. -func AfterRetryDelay(defaultDelay time.Duration, codes ...int) SendDecorator { - delay := time.Duration(0) - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - if delay > time.Duration(0) { - time.Sleep(delay) + if !DelayForBackoff(d, 1, r.Cancel) { + return nil, fmt.Errorf("autorest: AfterDelay canceled before full delay") } - resp, err := s.Do(r) - if ResponseRequiresPolling(resp, codes...) { - delay = GetPollingDelay(resp, defaultDelay) - } else { - delay = time.Duration(0) - } - return resp, err + return s.Do(r) }) } } @@ -104,19 +88,6 @@ func AsIs() SendDecorator { } } -// WithLogging returns a SendDecorator that implements simple before and after logging of the -// request. -func WithLogging(logger *log.Logger) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - logger.Printf("Sending %s %s\n", r.Method, r.URL) - resp, err := s.Do(r) - logger.Printf("%s %s received %s\n", r.Method, r.URL, resp.Status) - return resp, err - }) - } -} - // DoCloseIfError returns a SendDecorator that first invokes the passed Sender after which // it closes the response if the passed Sender returns an error and the response body exists. func DoCloseIfError() SendDecorator { @@ -139,7 +110,7 @@ func DoErrorIfStatusCode(codes ...int) SendDecorator { return SenderFunc(func(r *http.Request) (*http.Response, error) { resp, err := s.Do(r) if err == nil && ResponseHasStatusCode(resp, codes...) { - err = NewErrorWithStatusCode("autorest", "DoErrorIfStatusCode", resp.StatusCode, "%v %v failed with %s", + err = NewErrorWithResponse("autorest", "DoErrorIfStatusCode", resp, "%v %v failed with %s", resp.Request.Method, resp.Request.URL, resp.Status) @@ -157,7 +128,7 @@ func DoErrorUnlessStatusCode(codes ...int) SendDecorator { return SenderFunc(func(r *http.Request) (*http.Response, error) { resp, err := s.Do(r) if err == nil && !ResponseHasStatusCode(resp, codes...) { - err = NewErrorWithStatusCode("autorest", "DoErrorUnlessStatusCode", resp.StatusCode, "%v %v failed with %s", + err = NewErrorWithResponse("autorest", "DoErrorUnlessStatusCode", resp, "%v %v failed with %s", resp.Request.Method, resp.Request.URL, resp.Status) @@ -167,9 +138,37 @@ func DoErrorUnlessStatusCode(codes ...int) SendDecorator { } } -// DoRetryForAttempts returns a SendDecorator that retries the request for up to the specified +// DoPollForStatusCodes returns a SendDecorator that polls if the http.Response contains one of the +// passed status codes. It expects the http.Response to contain a Location header providing the +// URL at which to poll (using GET) and will poll until the time passed is equal to or greater than +// the supplied duration. It will delay between requests for the duration specified in the +// RetryAfter header or, if the header is absent, the passed delay. Polling may be canceled by +// closing the optional channel on the http.Request. +func DoPollForStatusCodes(duration time.Duration, delay time.Duration, codes ...int) SendDecorator { + return func(s Sender) Sender { + return SenderFunc(func(r *http.Request) (resp *http.Response, err error) { + resp, err = s.Do(r) + + if err == nil && ResponseHasStatusCode(resp, codes...) { + r, err = NewPollingRequest(resp, r.Cancel) + + for err == nil && ResponseHasStatusCode(resp, codes...) { + Respond(resp, + ByClosing()) + resp, err = SendWithSender(s, r, + AfterDelay(GetRetryAfter(resp, delay))) + } + } + + return resp, err + }) + } +} + +// DoRetryForAttempts returns a SendDecorator that retries a failed request for up to the specified // number of attempts, exponentially backing off between requests using the supplied backoff -// time.Duration (which may be zero). +// time.Duration (which may be zero). Retrying may be canceled by closing the optional channel on +// the http.Request. func DoRetryForAttempts(attempts int, backoff time.Duration) SendDecorator { return func(s Sender) Sender { return SenderFunc(func(r *http.Request) (resp *http.Response, err error) { @@ -178,7 +177,7 @@ func DoRetryForAttempts(attempts int, backoff time.Duration) SendDecorator { if err == nil { return resp, err } - DelayForBackoff(backoff, attempt) + DelayForBackoff(backoff, attempt, r.Cancel) } return resp, err }) @@ -187,7 +186,8 @@ func DoRetryForAttempts(attempts int, backoff time.Duration) SendDecorator { // DoRetryForDuration returns a SendDecorator that retries the request until the total time is equal // to or greater than the specified duration, exponentially backing off between requests using the -// supplied backoff time.Duration (which may be zero). +// supplied backoff time.Duration (which may be zero). Retrying may be canceled by closing the +// optional channel on the http.Request. func DoRetryForDuration(d time.Duration, backoff time.Duration) SendDecorator { return func(s Sender) Sender { return SenderFunc(func(r *http.Request) (resp *http.Response, err error) { @@ -197,15 +197,38 @@ func DoRetryForDuration(d time.Duration, backoff time.Duration) SendDecorator { if err == nil { return resp, err } - DelayForBackoff(backoff, attempt) + DelayForBackoff(backoff, attempt, r.Cancel) } return resp, err }) } } -// DelayForBackoff invokes time.Sleep for the supplied backoff duration raised to the power of -// passed attempt (i.e., an exponential backoff delay). Backoff may be zero. -func DelayForBackoff(backoff time.Duration, attempt int) { - time.Sleep(time.Duration(math.Pow(float64(backoff), float64(attempt)))) +// WithLogging returns a SendDecorator that implements simple before and after logging of the +// request. +func WithLogging(logger *log.Logger) SendDecorator { + return func(s Sender) Sender { + return SenderFunc(func(r *http.Request) (*http.Response, error) { + logger.Printf("Sending %s %s", r.Method, r.URL) + resp, err := s.Do(r) + if err != nil { + logger.Printf("%s %s received error '%v'", r.Method, r.URL, err) + } else { + logger.Printf("%s %s received %s", r.Method, r.URL, resp.Status) + } + return resp, err + }) + } +} + +// DelayForBackoff invokes time.After for the supplied backoff duration raised to the power of +// passed attempt (i.e., an exponential backoff delay). Backoff may be zero. The delay may be +// canceled by closing the passed channel. If terminated early, returns false. +func DelayForBackoff(backoff time.Duration, attempt int, cancel <-chan struct{}) bool { + select { + case <-time.After(time.Duration(math.Pow(float64(backoff), float64(attempt)))): + return true + case <-cancel: + return false + } } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/to/convert.go b/vendor/github.com/Azure/go-autorest/autorest/to/convert.go similarity index 100% rename from vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/to/convert.go rename to vendor/github.com/Azure/go-autorest/autorest/to/convert.go diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/utility.go b/vendor/github.com/Azure/go-autorest/autorest/utility.go similarity index 78% rename from vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/utility.go rename to vendor/github.com/Azure/go-autorest/autorest/utility.go index c373aa825e88..96ac779739b7 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/utility.go +++ b/vendor/github.com/Azure/go-autorest/autorest/utility.go @@ -46,6 +46,26 @@ func CopyAndDecode(encodedAs EncodedAs, r io.Reader, v interface{}) (bytes.Buffe return b, NewDecoder(encodedAs, io.TeeReader(r, &b)).Decode(v) } +// TeeReadCloser returns a ReadCloser that writes to w what it reads from rc. +// It utilizes io.TeeReader to copy the data read and has the same behavior when reading. +// Further, when it is closed, it ensures that rc is closed as well. +func TeeReadCloser(rc io.ReadCloser, w io.Writer) io.ReadCloser { + return &teeReadCloser{rc, io.TeeReader(rc, w)} +} + +type teeReadCloser struct { + rc io.ReadCloser + r io.Reader +} + +func (t *teeReadCloser) Read(p []byte) (int, error) { + return t.r.Read(p) +} + +func (t *teeReadCloser) Close() error { + return t.rc.Close() +} + func containsInt(ints []int, n int) bool { for _, i := range ints { if i == n { diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/version.go b/vendor/github.com/Azure/go-autorest/autorest/version.go similarity index 80% rename from vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/version.go rename to vendor/github.com/Azure/go-autorest/autorest/version.go index 685b1e6324e1..8031a332cd2d 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/version.go +++ b/vendor/github.com/Azure/go-autorest/autorest/version.go @@ -5,9 +5,9 @@ import ( ) const ( - major = "1" - minor = "1" - patch = "1" + major = "7" + minor = "0" + patch = "0" tag = "" semVerFormat = "%s.%s.%s%s" ) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/.gitignore b/vendor/github.com/dgrijalva/jwt-go/.gitignore similarity index 100% rename from vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/.gitignore rename to vendor/github.com/dgrijalva/jwt-go/.gitignore diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/.travis.yml b/vendor/github.com/dgrijalva/jwt-go/.travis.yml similarity index 100% rename from vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/.travis.yml rename to vendor/github.com/dgrijalva/jwt-go/.travis.yml diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/LICENSE b/vendor/github.com/dgrijalva/jwt-go/LICENSE similarity index 100% rename from vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/LICENSE rename to vendor/github.com/dgrijalva/jwt-go/LICENSE diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/README.md b/vendor/github.com/dgrijalva/jwt-go/README.md similarity index 60% rename from vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/README.md rename to vendor/github.com/dgrijalva/jwt-go/README.md index 001c0a338563..bf0100f4d825 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/README.md +++ b/vendor/github.com/dgrijalva/jwt-go/README.md @@ -14,7 +14,7 @@ The part in the middle is the interesting bit. It's called the Claims and conta ## What's in the box? -This library supports the parsing and verification as well as the generation and signing of JWTs. Current supported signing algorithms are RSA256 and HMAC SHA256, though hooks are present for adding your own. +This library supports the parsing and verification as well as the generation and signing of JWTs. Current supported signing algorithms are HMAC SHA, RSA, RSA-PSS, and ECDSA, though hooks are present for adding your own. ## Parse and Verify @@ -26,7 +26,7 @@ Parsing and verifying tokens is pretty straight forward. You pass in the token if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok { return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) } - return myLookupKey(token.Header["kid"]) + return myLookupKey(token.Header["kid"]), nil }) if err == nil && token.Valid { @@ -62,6 +62,35 @@ This project uses [Semantic Versioning 2.0.0](http://semver.org). Accepted pull While we try to make it obvious when we make breaking changes, there isn't a great mechanism for pushing announcements out to users. You may want to use this alternative package include: `gopkg.in/dgrijalva/jwt-go.v2`. It will do the right thing WRT semantic versioning. +## Usage Tips + +### Signing vs Encryption + +A token is simply a JSON object that is signed by its author. this tells you exactly two things about the data: + +* The author of the token was in the possession of the signing secret +* The data has not been modified since it was signed + +It's important to know that JWT does not provide encryption, which means anyone who has access to the token can read its contents. If you need to protect (encrypt) the data, there is a companion spec, `JWE`, that provides this functionality. JWE is currently outside the scope of this library. + +### Choosing a Signing Method + +There are several signing methods available, and you should probably take the time to learn about the various options before choosing one. The principal design decision is most likely going to be symmetric vs asymmetric. + +Symmetric signing methods, such as HSA, use only a single secret. This is probably the simplest signing method to use since any `[]byte` can be used as a valid secret. They are also slightly computationally faster to use, though this rarely is enough to matter. Symmetric signing methods work the best when both producers and consumers of tokens are trusted, or even the same system. Since the same secret is used to both sign and validate tokens, you can't easily distribute the key for validation. + +Asymmetric signing methods, such as RSA, use different keys for signing and verifying tokens. This makes it possible to produce tokens with a private key, and allow any consumer to access the public key for verification. + +### JWT and OAuth + +It's worth mentioning that OAuth and JWT are not the same thing. A JWT token is simply a signed JSON object. It can be used anywhere such a thing is useful. There is some confusion, though, as JWT is the most common type of bearer token used in OAuth2 authentication. + +Without going too far down the rabbit hole, here's a description of the interaction of these technologies: + +* OAuth is a protocol for allowing an identity provider to be separate from the service a user is logging in to. For example, whenever you use Facebook to log into a different service (Yelp, Spotify, etc), you are using OAuth. +* OAuth defines several options for passing around authentication data. One popular method is called a "bearer token". A bearer token is simply a string that _should_ only be held by an authenticated user. Thus, simply presenting this token proves your identity. You can probably derive from here why a JWT might make a good bearer token. +* Because bearer tokens are used for authentication, it's important they're kept secret. This is why transactions that use bearer tokens typically happen over SSL. + ## More Documentation can be found [on godoc.org](http://godoc.org/github.com/dgrijalva/jwt-go). diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md b/vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md similarity index 100% rename from vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md rename to vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/doc.go b/vendor/github.com/dgrijalva/jwt-go/doc.go similarity index 100% rename from vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/doc.go rename to vendor/github.com/dgrijalva/jwt-go/doc.go diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/ecdsa.go b/vendor/github.com/dgrijalva/jwt-go/ecdsa.go similarity index 100% rename from vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/ecdsa.go rename to vendor/github.com/dgrijalva/jwt-go/ecdsa.go diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/ecdsa_utils.go b/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go similarity index 100% rename from vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/ecdsa_utils.go rename to vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/errors.go b/vendor/github.com/dgrijalva/jwt-go/errors.go similarity index 100% rename from vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/errors.go rename to vendor/github.com/dgrijalva/jwt-go/errors.go diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/hmac.go b/vendor/github.com/dgrijalva/jwt-go/hmac.go similarity index 100% rename from vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/hmac.go rename to vendor/github.com/dgrijalva/jwt-go/hmac.go diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/parser.go b/vendor/github.com/dgrijalva/jwt-go/parser.go similarity index 94% rename from vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/parser.go rename to vendor/github.com/dgrijalva/jwt-go/parser.go index 3fc27bfeddd1..a078404ec561 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/parser.go +++ b/vendor/github.com/dgrijalva/jwt-go/parser.go @@ -26,6 +26,9 @@ func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { // parse Header var headerBytes []byte if headerBytes, err = DecodeSegment(parts[0]); err != nil { + if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") { + return token, &ValidationError{err: "tokenstring should not contain 'bearer '", Errors: ValidationErrorMalformed} + } return token, &ValidationError{err: err.Error(), Errors: ValidationErrorMalformed} } if err = json.Unmarshal(headerBytes, &token.Header); err != nil { diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/rsa.go b/vendor/github.com/dgrijalva/jwt-go/rsa.go similarity index 100% rename from vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/rsa.go rename to vendor/github.com/dgrijalva/jwt-go/rsa.go diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/rsa_pss.go b/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go similarity index 100% rename from vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/rsa_pss.go rename to vendor/github.com/dgrijalva/jwt-go/rsa_pss.go diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/rsa_utils.go b/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go similarity index 100% rename from vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/rsa_utils.go rename to vendor/github.com/dgrijalva/jwt-go/rsa_utils.go diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/signing_method.go b/vendor/github.com/dgrijalva/jwt-go/signing_method.go similarity index 100% rename from vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/signing_method.go rename to vendor/github.com/dgrijalva/jwt-go/signing_method.go diff --git a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/token.go b/vendor/github.com/dgrijalva/jwt-go/token.go similarity index 98% rename from vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/token.go rename to vendor/github.com/dgrijalva/jwt-go/token.go index d35aaa4a930b..1cf267d44a54 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/dgrijalva/jwt-go/token.go +++ b/vendor/github.com/dgrijalva/jwt-go/token.go @@ -96,7 +96,7 @@ func ParseFromRequest(req *http.Request, keyFunc Keyfunc) (token *Token, err err // Look for an Authorization header if ah := req.Header.Get("Authorization"); ah != "" { // Should be a bearer token - if len(ah) > 6 && strings.ToUpper(ah[0:6]) == "BEARER" { + if len(ah) > 6 && strings.ToUpper(ah[0:7]) == "BEARER " { return Parse(ah[7:], keyFunc) } } From 0769674c54ac666241b0c06a352a15649ca2b0f8 Mon Sep 17 00:00:00 2001 From: James Nugent Date: Wed, 1 Jun 2016 15:17:21 -0500 Subject: [PATCH 02/17] provider/azurerm: Use new library configuration Most resources are commented out at this stage, as they require surgery to make them work with the new world of the Azure SDK. --- builtin/providers/azurerm/config.go | 42 +- builtin/providers/azurerm/provider.go | 109 +- .../azurerm/resource_arm_availability_set.go | 14 +- .../azurerm/resource_arm_cdn_endpoint.go | 898 +++---- .../azurerm/resource_arm_cdn_endpoint_test.go | 426 ++-- .../azurerm/resource_arm_cdn_profile.go | 368 +-- .../azurerm/resource_arm_cdn_profile_test.go | 410 +-- .../resource_arm_local_network_gateway.go | 268 +- ...resource_arm_local_network_gateway_test.go | 212 +- .../resource_arm_network_interface_card.go | 858 +++---- ...esource_arm_network_interface_card_test.go | 579 ++--- .../resource_arm_network_security_group.go | 598 ++--- ...esource_arm_network_security_group_test.go | 526 ++-- .../resource_arm_network_security_rule.go | 434 ++-- ...resource_arm_network_security_rule_test.go | 402 +-- .../azurerm/resource_arm_public_ip.go | 498 ++-- .../azurerm/resource_arm_public_ip_test.go | 628 ++--- .../providers/azurerm/resource_arm_route.go | 318 +-- .../azurerm/resource_arm_route_table.go | 512 ++-- .../azurerm/resource_arm_route_table_test.go | 584 ++--- .../azurerm/resource_arm_route_test.go | 314 +-- .../azurerm/resource_arm_storage_account.go | 614 ++--- .../resource_arm_storage_account_test.go | 328 +-- .../azurerm/resource_arm_storage_blob.go | 14 +- .../azurerm/resource_arm_storage_container.go | 450 ++-- .../resource_arm_storage_container_test.go | 478 ++-- .../azurerm/resource_arm_storage_queue.go | 4 +- .../providers/azurerm/resource_arm_subnet.go | 372 +-- .../azurerm/resource_arm_subnet_test.go | 212 +- .../resource_arm_template_deployment.go | 422 +-- .../resource_arm_template_deployment_test.go | 498 ++-- .../azurerm/resource_arm_virtual_machine.go | 2266 ++++++++--------- .../resource_arm_virtual_machine_test.go | 1016 ++++---- .../azurerm/resource_arm_virtual_network.go | 510 ++-- 34 files changed, 8075 insertions(+), 8107 deletions(-) diff --git a/builtin/providers/azurerm/config.go b/builtin/providers/azurerm/config.go index 0a84852d0b01..535f03392b4a 100644 --- a/builtin/providers/azurerm/config.go +++ b/builtin/providers/azurerm/config.go @@ -4,10 +4,7 @@ import ( "fmt" "log" "net/http" - "time" - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/azure-sdk-for-go/arm/cdn" "github.com/Azure/azure-sdk-for-go/arm/compute" "github.com/Azure/azure-sdk-for-go/arm/network" @@ -15,6 +12,8 @@ import ( "github.com/Azure/azure-sdk-for-go/arm/scheduler" "github.com/Azure/azure-sdk-for-go/arm/storage" mainStorage "github.com/Azure/azure-sdk-for-go/storage" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" "github.com/hashicorp/terraform/terraform" riviera "github.com/jen20/riviera/azure" ) @@ -77,22 +76,6 @@ func withRequestLogging() autorest.SendDecorator { } } -func withPollWatcher() autorest.SendDecorator { - return func(s autorest.Sender) autorest.Sender { - return autorest.SenderFunc(func(r *http.Request) (*http.Response, error) { - fmt.Printf("[DEBUG] Sending Azure RM Request %q to %q\n", r.Method, r.URL) - resp, err := s.Do(r) - fmt.Printf("[DEBUG] Received Azure RM Request status code %s for %s\n", resp.Status, r.URL) - if autorest.ResponseRequiresPolling(resp) { - fmt.Printf("[DEBUG] Azure RM request will poll %s after %d seconds\n", - autorest.GetPollingLocation(resp), - int(autorest.GetPollingDelay(resp, time.Duration(0))/time.Second)) - } - return resp, err - }) - } -} - func setUserAgent(client *autorest.Client) { var version string if terraform.VersionPrerelease != "" { @@ -130,7 +113,23 @@ func (c *Config) getArmClient() (*ArmClient, error) { } client.rivieraClient = rivieraClient - spt, err := azure.NewServicePrincipalToken(c.ClientID, c.ClientSecret, c.TenantID, azure.AzureResourceManagerScope) + oauthConfig, err := azure.PublicCloud.OAuthConfigForTenant(c.TenantID) + if err != nil { + return nil, err + } + + // This is necessary because no-one thought about API usability. OAuthConfigForTenant + // returns a pointer, which can be nil. NewServicePrincipalToken does not take a pointer. + // Consequently we have to nil check this and do _something_ if it is nil, which should + // be either an invariant of OAuthConfigForTenant (guarantee the token is not nil if + // there is no error), or NewServicePrincipalToken should error out if the configuration + // is required and is nil. This is the worst of all worlds, however. + if oauthConfig == nil { + return nil, fmt.Errorf("Unable to configure OAuthConfig for tenant %s", c.TenantID) + } + + spt, err := azure.NewServicePrincipalToken(*oauthConfig, c.ClientID, c.ClientSecret, + azure.PublicCloud.ResourceManagerEndpoint) if err != nil { return nil, err } @@ -284,7 +283,7 @@ func (c *Config) getArmClient() (*ArmClient, error) { ssc := storage.NewAccountsClient(c.SubscriptionID) setUserAgent(&ssc.Client) ssc.Authorizer = spt - ssc.Sender = autorest.CreateSender(withRequestLogging(), withPollWatcher()) + ssc.Sender = autorest.CreateSender(withRequestLogging()) client.storageServiceClient = ssc suc := storage.NewUsageOperationsClient(c.SubscriptionID) @@ -349,6 +348,7 @@ func (armClient *ArmClient) getBlobStorageClientForStorageAccount(resourceGroupN blobClient := storageClient.GetBlobService() return &blobClient, true, nil } + func (armClient *ArmClient) getQueueServiceClientForStorageAccount(resourceGroupName, storageAccountName string) (*mainStorage.QueueServiceClient, bool, error) { key, accountExists, err := armClient.getKeyForStorageAccount(resourceGroupName, storageAccountName) if err != nil { diff --git a/builtin/providers/azurerm/provider.go b/builtin/providers/azurerm/provider.go index f0852ee8af86..4709d95a414c 100644 --- a/builtin/providers/azurerm/provider.go +++ b/builtin/providers/azurerm/provider.go @@ -2,12 +2,9 @@ package azurerm import ( "fmt" - "log" - "net/http" "reflect" "strings" - "github.com/Azure/azure-sdk-for-go/Godeps/_workspace/src/github.com/Azure/go-autorest/autorest" "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform/helper/mutexkv" "github.com/hashicorp/terraform/helper/resource" @@ -21,25 +18,25 @@ import ( func Provider() terraform.ResourceProvider { return &schema.Provider{ Schema: map[string]*schema.Schema{ - "subscription_id": &schema.Schema{ + "subscription_id": { Type: schema.TypeString, Required: true, DefaultFunc: schema.EnvDefaultFunc("ARM_SUBSCRIPTION_ID", ""), }, - "client_id": &schema.Schema{ + "client_id": { Type: schema.TypeString, Required: true, DefaultFunc: schema.EnvDefaultFunc("ARM_CLIENT_ID", ""), }, - "client_secret": &schema.Schema{ + "client_secret": { Type: schema.TypeString, Required: true, DefaultFunc: schema.EnvDefaultFunc("ARM_CLIENT_SECRET", ""), }, - "tenant_id": &schema.Schema{ + "tenant_id": { Type: schema.TypeString, Required: true, DefaultFunc: schema.EnvDefaultFunc("ARM_TENANT_ID", ""), @@ -47,37 +44,40 @@ func Provider() terraform.ResourceProvider { }, ResourcesMap: map[string]*schema.Resource{ - "azurerm_availability_set": resourceArmAvailabilitySet(), - "azurerm_cdn_endpoint": resourceArmCdnEndpoint(), - "azurerm_cdn_profile": resourceArmCdnProfile(), - "azurerm_dns_a_record": resourceArmDnsARecord(), - "azurerm_dns_aaaa_record": resourceArmDnsAAAARecord(), - "azurerm_dns_cname_record": resourceArmDnsCNameRecord(), - "azurerm_dns_mx_record": resourceArmDnsMxRecord(), - "azurerm_dns_ns_record": resourceArmDnsNsRecord(), - "azurerm_dns_srv_record": resourceArmDnsSrvRecord(), - "azurerm_dns_txt_record": resourceArmDnsTxtRecord(), - "azurerm_dns_zone": resourceArmDnsZone(), - "azurerm_local_network_gateway": resourceArmLocalNetworkGateway(), - "azurerm_network_interface": resourceArmNetworkInterface(), - "azurerm_network_security_group": resourceArmNetworkSecurityGroup(), - "azurerm_network_security_rule": resourceArmNetworkSecurityRule(), - "azurerm_public_ip": resourceArmPublicIp(), - "azurerm_resource_group": resourceArmResourceGroup(), - "azurerm_route": resourceArmRoute(), - "azurerm_route_table": resourceArmRouteTable(), - "azurerm_search_service": resourceArmSearchService(), - "azurerm_sql_database": resourceArmSqlDatabase(), - "azurerm_sql_firewall_rule": resourceArmSqlFirewallRule(), - "azurerm_sql_server": resourceArmSqlServer(), - "azurerm_storage_account": resourceArmStorageAccount(), - "azurerm_storage_blob": resourceArmStorageBlob(), - "azurerm_storage_container": resourceArmStorageContainer(), - "azurerm_storage_queue": resourceArmStorageQueue(), - "azurerm_subnet": resourceArmSubnet(), - "azurerm_template_deployment": resourceArmTemplateDeployment(), - "azurerm_virtual_machine": resourceArmVirtualMachine(), - "azurerm_virtual_network": resourceArmVirtualNetwork(), + // These resources use the Azure ARM SDK + "azurerm_availability_set": resourceArmAvailabilitySet(), + //"azurerm_cdn_endpoint": resourceArmCdnEndpoint(), + //"azurerm_cdn_profile": resourceArmCdnProfile(), + //"azurerm_local_network_gateway": resourceArmLocalNetworkGateway(), + //"azurerm_network_interface": resourceArmNetworkInterface(), + //"azurerm_network_security_group": resourceArmNetworkSecurityGroup(), + //"azurerm_network_security_rule": resourceArmNetworkSecurityRule(), + //"azurerm_public_ip": resourceArmPublicIp(), + //"azurerm_route": resourceArmRoute(), + //"azurerm_route_table": resourceArmRouteTable(), + //"azurerm_storage_account": resourceArmStorageAccount(), + "azurerm_storage_blob": resourceArmStorageBlob(), + //"azurerm_storage_container": resourceArmStorageContainer(), + "azurerm_storage_queue": resourceArmStorageQueue(), + //"azurerm_subnet": resourceArmSubnet(), + //"azurerm_template_deployment": resourceArmTemplateDeployment(), + //"azurerm_virtual_machine": resourceArmVirtualMachine(), + //"azurerm_virtual_network": resourceArmVirtualNetwork(), + + // These resources use the Riviera SDK + "azurerm_dns_a_record": resourceArmDnsARecord(), + "azurerm_dns_aaaa_record": resourceArmDnsAAAARecord(), + "azurerm_dns_cname_record": resourceArmDnsCNameRecord(), + "azurerm_dns_mx_record": resourceArmDnsMxRecord(), + "azurerm_dns_ns_record": resourceArmDnsNsRecord(), + "azurerm_dns_srv_record": resourceArmDnsSrvRecord(), + "azurerm_dns_txt_record": resourceArmDnsTxtRecord(), + "azurerm_dns_zone": resourceArmDnsZone(), + "azurerm_resource_group": resourceArmResourceGroup(), + "azurerm_search_service": resourceArmSearchService(), + "azurerm_sql_database": resourceArmSqlDatabase(), + "azurerm_sql_firewall_rule": resourceArmSqlFirewallRule(), + "azurerm_sql_server": resourceArmSqlServer(), }, ConfigureFunc: providerConfigure, } @@ -197,39 +197,6 @@ func azureRMNormalizeLocation(location interface{}) string { return strings.Replace(strings.ToLower(input), " ", "", -1) } -// pollIndefinitelyAsNeeded is a terrible hack which is necessary because the Azure -// Storage API (and perhaps others) can have response times way beyond the default -// retry timeouts, with no apparent upper bound. This effectively causes the client -// to continue polling when it reaches the configured timeout. My investigations -// suggest that this is neccesary when deleting and recreating a storage account with -// the same name in a short (though undetermined) time period. -// -// It is possible that this will give Terraform the appearance of being slow in -// future: I have attempted to mitigate this by logging whenever this happens. We -// may want to revisit this with configurable timeouts in the future as clearly -// unbounded wait loops is not ideal. It does seem preferable to the current situation -// where our polling loop will time out _with an operation in progress_, but no ID -// for the resource - so the state will not know about it, and conflicts will occur -// on the next run. -func pollIndefinitelyAsNeeded(client autorest.Client, response *http.Response, acceptableCodes ...int) (*http.Response, error) { - var resp *http.Response - var err error - - for { - resp, err = client.PollAsNeeded(response, acceptableCodes...) - if err != nil { - if resp.StatusCode != http.StatusAccepted { - log.Printf("[DEBUG] Starting new polling loop for %q", response.Request.URL.Path) - continue - } - - return resp, err - } - - return resp, nil - } -} - // armMutexKV is the instance of MutexKV for ARM resources var armMutexKV = mutexkv.NewMutexKV() diff --git a/builtin/providers/azurerm/resource_arm_availability_set.go b/builtin/providers/azurerm/resource_arm_availability_set.go index 74efc886d017..3e37a0a3f22c 100644 --- a/builtin/providers/azurerm/resource_arm_availability_set.go +++ b/builtin/providers/azurerm/resource_arm_availability_set.go @@ -17,26 +17,26 @@ func resourceArmAvailabilitySet() *schema.Resource { Delete: resourceArmAvailabilitySetDelete, Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ + "name": { Type: schema.TypeString, Required: true, ForceNew: true, }, - "resource_group_name": &schema.Schema{ + "resource_group_name": { Type: schema.TypeString, Required: true, ForceNew: true, }, - "location": &schema.Schema{ + "location": { Type: schema.TypeString, Required: true, ForceNew: true, StateFunc: azureRMNormalizeLocation, }, - "platform_update_domain_count": &schema.Schema{ + "platform_update_domain_count": { Type: schema.TypeInt, Optional: true, Default: 5, @@ -50,7 +50,7 @@ func resourceArmAvailabilitySet() *schema.Resource { }, }, - "platform_fault_domain_count": &schema.Schema{ + "platform_fault_domain_count": { Type: schema.TypeInt, Optional: true, Default: 3, @@ -78,8 +78,8 @@ func resourceArmAvailabilitySetCreate(d *schema.ResourceData, meta interface{}) name := d.Get("name").(string) location := d.Get("location").(string) resGroup := d.Get("resource_group_name").(string) - updateDomainCount := d.Get("platform_update_domain_count").(int) - faultDomainCount := d.Get("platform_fault_domain_count").(int) + updateDomainCount := d.Get("platform_update_domain_count").(int32) + faultDomainCount := d.Get("platform_fault_domain_count").(int32) tags := d.Get("tags").(map[string]interface{}) availSet := compute.AvailabilitySet{ diff --git a/builtin/providers/azurerm/resource_arm_cdn_endpoint.go b/builtin/providers/azurerm/resource_arm_cdn_endpoint.go index 42d0f78f1a3b..01c290fa9e03 100644 --- a/builtin/providers/azurerm/resource_arm_cdn_endpoint.go +++ b/builtin/providers/azurerm/resource_arm_cdn_endpoint.go @@ -1,451 +1,451 @@ package azurerm -import ( - "bytes" - "fmt" - "log" - "net/http" - "strings" - "time" - - "github.com/Azure/azure-sdk-for-go/arm/cdn" - "github.com/hashicorp/terraform/helper/hashcode" - "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/helper/schema" -) - -func resourceArmCdnEndpoint() *schema.Resource { - return &schema.Resource{ - Create: resourceArmCdnEndpointCreate, - Read: resourceArmCdnEndpointRead, - Update: resourceArmCdnEndpointUpdate, - Delete: resourceArmCdnEndpointDelete, - - Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - - "location": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - StateFunc: azureRMNormalizeLocation, - }, - - "resource_group_name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - - "profile_name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - - "origin_host_header": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Computed: true, - }, - - "is_http_allowed": &schema.Schema{ - Type: schema.TypeBool, - Optional: true, - Default: true, - }, - - "is_https_allowed": &schema.Schema{ - Type: schema.TypeBool, - Optional: true, - Default: true, - }, - - "origin": &schema.Schema{ - Type: schema.TypeSet, - Required: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - - "host_name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - - "http_port": &schema.Schema{ - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - - "https_port": &schema.Schema{ - Type: schema.TypeInt, - Optional: true, - Computed: true, - }, - }, - }, - Set: resourceArmCdnEndpointOriginHash, - }, - - "origin_path": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Computed: true, - }, - - "querystring_caching_behaviour": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Default: "IgnoreQueryString", - ValidateFunc: validateCdnEndpointQuerystringCachingBehaviour, - }, - - "content_types_to_compress": &schema.Schema{ - Type: schema.TypeSet, - Optional: true, - Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - - "is_compression_enabled": &schema.Schema{ - Type: schema.TypeBool, - Optional: true, - Default: false, - }, - - "host_name": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - }, - - "tags": tagsSchema(), - }, - } -} - -func resourceArmCdnEndpointCreate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient) - cdnEndpointsClient := client.cdnEndpointsClient - - log.Printf("[INFO] preparing arguments for Azure ARM CDN EndPoint creation.") - - name := d.Get("name").(string) - location := d.Get("location").(string) - resGroup := d.Get("resource_group_name").(string) - profileName := d.Get("profile_name").(string) - http_allowed := d.Get("is_http_allowed").(bool) - https_allowed := d.Get("is_https_allowed").(bool) - compression_enabled := d.Get("is_compression_enabled").(bool) - caching_behaviour := d.Get("querystring_caching_behaviour").(string) - tags := d.Get("tags").(map[string]interface{}) - - properties := cdn.EndpointPropertiesCreateUpdateParameters{ - IsHTTPAllowed: &http_allowed, - IsHTTPSAllowed: &https_allowed, - IsCompressionEnabled: &compression_enabled, - QueryStringCachingBehavior: cdn.QueryStringCachingBehavior(caching_behaviour), - } - - origins, originsErr := expandAzureRmCdnEndpointOrigins(d) - if originsErr != nil { - return fmt.Errorf("Error Building list of CDN Endpoint Origins: %s", originsErr) - } - if len(origins) > 0 { - properties.Origins = &origins - } - - if v, ok := d.GetOk("origin_host_header"); ok { - host_header := v.(string) - properties.OriginHostHeader = &host_header - } - - if v, ok := d.GetOk("origin_path"); ok { - origin_path := v.(string) - properties.OriginPath = &origin_path - } - - if v, ok := d.GetOk("content_types_to_compress"); ok { - var content_types []string - ctypes := v.(*schema.Set).List() - for _, ct := range ctypes { - str := ct.(string) - content_types = append(content_types, str) - } - - properties.ContentTypesToCompress = &content_types - } - - cdnEndpoint := cdn.EndpointCreateParameters{ - Location: &location, - Properties: &properties, - Tags: expandTags(tags), - } - - resp, err := cdnEndpointsClient.Create(name, cdnEndpoint, profileName, resGroup) - if err != nil { - return err - } - - d.SetId(*resp.ID) - - log.Printf("[DEBUG] Waiting for CDN Endpoint (%s) to become available", name) - stateConf := &resource.StateChangeConf{ - Pending: []string{"Accepted", "Updating", "Creating"}, - Target: []string{"Succeeded"}, - Refresh: cdnEndpointStateRefreshFunc(client, resGroup, profileName, name), - Timeout: 10 * time.Minute, - } - if _, err := stateConf.WaitForState(); err != nil { - return fmt.Errorf("Error waiting for CDN Endpoint (%s) to become available: %s", name, err) - } - - return resourceArmCdnEndpointRead(d, meta) -} - -func resourceArmCdnEndpointRead(d *schema.ResourceData, meta interface{}) error { - cdnEndpointsClient := meta.(*ArmClient).cdnEndpointsClient - - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - resGroup := id.ResourceGroup - name := id.Path["endpoints"] - profileName := id.Path["profiles"] - if profileName == "" { - profileName = id.Path["Profiles"] - } - log.Printf("[INFO] Trying to find the AzureRM CDN Endpoint %s (Profile: %s, RG: %s)", name, profileName, resGroup) - resp, err := cdnEndpointsClient.Get(name, profileName, resGroup) - if resp.StatusCode == http.StatusNotFound { - d.SetId("") - return nil - } - if err != nil { - return fmt.Errorf("Error making Read request on Azure CDN Endpoint %s: %s", name, err) - } - - d.Set("name", resp.Name) - d.Set("host_name", resp.Properties.HostName) - d.Set("is_compression_enabled", resp.Properties.IsCompressionEnabled) - d.Set("is_http_allowed", resp.Properties.IsHTTPAllowed) - d.Set("is_https_allowed", resp.Properties.IsHTTPSAllowed) - d.Set("querystring_caching_behaviour", resp.Properties.QueryStringCachingBehavior) - if resp.Properties.OriginHostHeader != nil && *resp.Properties.OriginHostHeader != "" { - d.Set("origin_host_header", resp.Properties.OriginHostHeader) - } - if resp.Properties.OriginPath != nil && *resp.Properties.OriginPath != "" { - d.Set("origin_path", resp.Properties.OriginPath) - } - if resp.Properties.ContentTypesToCompress != nil && len(*resp.Properties.ContentTypesToCompress) > 0 { - d.Set("content_types_to_compress", flattenAzureRMCdnEndpointContentTypes(resp.Properties.ContentTypesToCompress)) - } - d.Set("origin", flattenAzureRMCdnEndpointOrigin(resp.Properties.Origins)) - - flattenAndSetTags(d, resp.Tags) - - return nil -} - -func resourceArmCdnEndpointUpdate(d *schema.ResourceData, meta interface{}) error { - cdnEndpointsClient := meta.(*ArmClient).cdnEndpointsClient - - if !d.HasChange("tags") { - return nil - } - - name := d.Get("name").(string) - resGroup := d.Get("resource_group_name").(string) - profileName := d.Get("profile_name").(string) - http_allowed := d.Get("is_http_allowed").(bool) - https_allowed := d.Get("is_https_allowed").(bool) - compression_enabled := d.Get("is_compression_enabled").(bool) - caching_behaviour := d.Get("querystring_caching_behaviour").(string) - newTags := d.Get("tags").(map[string]interface{}) - - properties := cdn.EndpointPropertiesCreateUpdateParameters{ - IsHTTPAllowed: &http_allowed, - IsHTTPSAllowed: &https_allowed, - IsCompressionEnabled: &compression_enabled, - QueryStringCachingBehavior: cdn.QueryStringCachingBehavior(caching_behaviour), - } - - if d.HasChange("origin") { - origins, originsErr := expandAzureRmCdnEndpointOrigins(d) - if originsErr != nil { - return fmt.Errorf("Error Building list of CDN Endpoint Origins: %s", originsErr) - } - if len(origins) > 0 { - properties.Origins = &origins - } - } - - if d.HasChange("origin_host_header") { - host_header := d.Get("origin_host_header").(string) - properties.OriginHostHeader = &host_header - } - - if d.HasChange("origin_path") { - origin_path := d.Get("origin_path").(string) - properties.OriginPath = &origin_path - } - - if d.HasChange("content_types_to_compress") { - var content_types []string - ctypes := d.Get("content_types_to_compress").(*schema.Set).List() - for _, ct := range ctypes { - str := ct.(string) - content_types = append(content_types, str) - } - - properties.ContentTypesToCompress = &content_types - } - - updateProps := cdn.EndpointUpdateParameters{ - Tags: expandTags(newTags), - Properties: &properties, - } - - _, err := cdnEndpointsClient.Update(name, updateProps, profileName, resGroup) - if err != nil { - return fmt.Errorf("Error issuing Azure ARM update request to update CDN Endpoint %q: %s", name, err) - } - - return resourceArmCdnEndpointRead(d, meta) -} - -func resourceArmCdnEndpointDelete(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient).cdnEndpointsClient - - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - resGroup := id.ResourceGroup - profileName := id.Path["profiles"] - if profileName == "" { - profileName = id.Path["Profiles"] - } - name := id.Path["endpoints"] - - accResp, err := client.DeleteIfExists(name, profileName, resGroup) - if err != nil { - if accResp.StatusCode == http.StatusNotFound { - return nil - } - return fmt.Errorf("Error issuing AzureRM delete request for CDN Endpoint %q: %s", name, err) - } - _, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response, http.StatusNotFound) - if err != nil { - return fmt.Errorf("Error polling for AzureRM delete request for CDN Endpoint %q: %s", name, err) - } - - return err -} - -func cdnEndpointStateRefreshFunc(client *ArmClient, resourceGroupName string, profileName string, name string) resource.StateRefreshFunc { - return func() (interface{}, string, error) { - res, err := client.cdnEndpointsClient.Get(name, profileName, resourceGroupName) - if err != nil { - return nil, "", fmt.Errorf("Error issuing read request in cdnEndpointStateRefreshFunc to Azure ARM for CDN Endpoint '%s' (RG: '%s'): %s", name, resourceGroupName, err) - } - return res, string(res.Properties.ProvisioningState), nil - } -} - -func validateCdnEndpointQuerystringCachingBehaviour(v interface{}, k string) (ws []string, errors []error) { - value := strings.ToLower(v.(string)) - cachingTypes := map[string]bool{ - "ignorequerystring": true, - "bypasscaching": true, - "usequerystring": true, - } - - if !cachingTypes[value] { - errors = append(errors, fmt.Errorf("CDN Endpoint querystringCachingBehaviours can only be IgnoreQueryString, BypassCaching or UseQueryString")) - } - return -} - -func resourceArmCdnEndpointOriginHash(v interface{}) int { - var buf bytes.Buffer - m := v.(map[string]interface{}) - buf.WriteString(fmt.Sprintf("%s-", m["name"].(string))) - buf.WriteString(fmt.Sprintf("%s-", m["host_name"].(string))) - - return hashcode.String(buf.String()) -} - -func expandAzureRmCdnEndpointOrigins(d *schema.ResourceData) ([]cdn.DeepCreatedOrigin, error) { - configs := d.Get("origin").(*schema.Set).List() - origins := make([]cdn.DeepCreatedOrigin, 0, len(configs)) - - for _, configRaw := range configs { - data := configRaw.(map[string]interface{}) - - host_name := data["host_name"].(string) - - properties := cdn.DeepCreatedOriginProperties{ - HostName: &host_name, - } - - if v, ok := data["https_port"]; ok { - https_port := v.(int) - properties.HTTPSPort = &https_port - - } - - if v, ok := data["http_port"]; ok { - http_port := v.(int) - properties.HTTPPort = &http_port - } - - name := data["name"].(string) - - origin := cdn.DeepCreatedOrigin{ - Name: &name, - Properties: &properties, - } - - origins = append(origins, origin) - } - - return origins, nil -} - -func flattenAzureRMCdnEndpointOrigin(list *[]cdn.DeepCreatedOrigin) []map[string]interface{} { - result := make([]map[string]interface{}, 0, len(*list)) - for _, i := range *list { - l := map[string]interface{}{ - "name": *i.Name, - "host_name": *i.Properties.HostName, - } - - if i.Properties.HTTPPort != nil { - l["http_port"] = *i.Properties.HTTPPort - } - if i.Properties.HTTPSPort != nil { - l["https_port"] = *i.Properties.HTTPSPort - } - result = append(result, l) - } - return result -} - -func flattenAzureRMCdnEndpointContentTypes(list *[]string) []interface{} { - vs := make([]interface{}, 0, len(*list)) - for _, v := range *list { - vs = append(vs, v) - } - return vs -} +//import ( +// "bytes" +// "fmt" +// "log" +// "net/http" +// "strings" +// "time" +// +// "github.com/Azure/azure-sdk-for-go/arm/cdn" +// "github.com/hashicorp/terraform/helper/hashcode" +// "github.com/hashicorp/terraform/helper/resource" +// "github.com/hashicorp/terraform/helper/schema" +//) +// +//func resourceArmCdnEndpoint() *schema.Resource { +// return &schema.Resource{ +// Create: resourceArmCdnEndpointCreate, +// Read: resourceArmCdnEndpointRead, +// Update: resourceArmCdnEndpointUpdate, +// Delete: resourceArmCdnEndpointDelete, +// +// Schema: map[string]*schema.Schema{ +// "name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// }, +// +// "location": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// StateFunc: azureRMNormalizeLocation, +// }, +// +// "resource_group_name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// }, +// +// "profile_name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// }, +// +// "origin_host_header": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// Computed: true, +// }, +// +// "is_http_allowed": &schema.Schema{ +// Type: schema.TypeBool, +// Optional: true, +// Default: true, +// }, +// +// "is_https_allowed": &schema.Schema{ +// Type: schema.TypeBool, +// Optional: true, +// Default: true, +// }, +// +// "origin": &schema.Schema{ +// Type: schema.TypeSet, +// Required: true, +// Elem: &schema.Resource{ +// Schema: map[string]*schema.Schema{ +// "name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "host_name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "http_port": &schema.Schema{ +// Type: schema.TypeInt, +// Optional: true, +// Computed: true, +// }, +// +// "https_port": &schema.Schema{ +// Type: schema.TypeInt, +// Optional: true, +// Computed: true, +// }, +// }, +// }, +// Set: resourceArmCdnEndpointOriginHash, +// }, +// +// "origin_path": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// Computed: true, +// }, +// +// "querystring_caching_behaviour": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// Default: "IgnoreQueryString", +// ValidateFunc: validateCdnEndpointQuerystringCachingBehaviour, +// }, +// +// "content_types_to_compress": &schema.Schema{ +// Type: schema.TypeSet, +// Optional: true, +// Computed: true, +// Elem: &schema.Schema{Type: schema.TypeString}, +// Set: schema.HashString, +// }, +// +// "is_compression_enabled": &schema.Schema{ +// Type: schema.TypeBool, +// Optional: true, +// Default: false, +// }, +// +// "host_name": &schema.Schema{ +// Type: schema.TypeString, +// Computed: true, +// }, +// +// "tags": tagsSchema(), +// }, +// } +//} +// +//func resourceArmCdnEndpointCreate(d *schema.ResourceData, meta interface{}) error { +// client := meta.(*ArmClient) +// cdnEndpointsClient := client.cdnEndpointsClient +// +// log.Printf("[INFO] preparing arguments for Azure ARM CDN EndPoint creation.") +// +// name := d.Get("name").(string) +// location := d.Get("location").(string) +// resGroup := d.Get("resource_group_name").(string) +// profileName := d.Get("profile_name").(string) +// http_allowed := d.Get("is_http_allowed").(bool) +// https_allowed := d.Get("is_https_allowed").(bool) +// compression_enabled := d.Get("is_compression_enabled").(bool) +// caching_behaviour := d.Get("querystring_caching_behaviour").(string) +// tags := d.Get("tags").(map[string]interface{}) +// +// properties := cdn.EndpointPropertiesCreateUpdateParameters{ +// IsHTTPAllowed: &http_allowed, +// IsHTTPSAllowed: &https_allowed, +// IsCompressionEnabled: &compression_enabled, +// QueryStringCachingBehavior: cdn.QueryStringCachingBehavior(caching_behaviour), +// } +// +// origins, originsErr := expandAzureRmCdnEndpointOrigins(d) +// if originsErr != nil { +// return fmt.Errorf("Error Building list of CDN Endpoint Origins: %s", originsErr) +// } +// if len(origins) > 0 { +// properties.Origins = &origins +// } +// +// if v, ok := d.GetOk("origin_host_header"); ok { +// host_header := v.(string) +// properties.OriginHostHeader = &host_header +// } +// +// if v, ok := d.GetOk("origin_path"); ok { +// origin_path := v.(string) +// properties.OriginPath = &origin_path +// } +// +// if v, ok := d.GetOk("content_types_to_compress"); ok { +// var content_types []string +// ctypes := v.(*schema.Set).List() +// for _, ct := range ctypes { +// str := ct.(string) +// content_types = append(content_types, str) +// } +// +// properties.ContentTypesToCompress = &content_types +// } +// +// cdnEndpoint := cdn.EndpointCreateParameters{ +// Location: &location, +// Properties: &properties, +// Tags: expandTags(tags), +// } +// +// resp, err := cdnEndpointsClient.Create(name, cdnEndpoint, profileName, resGroup) +// if err != nil { +// return err +// } +// +// d.SetId(*resp.ID) +// +// log.Printf("[DEBUG] Waiting for CDN Endpoint (%s) to become available", name) +// stateConf := &resource.StateChangeConf{ +// Pending: []string{"Accepted", "Updating", "Creating"}, +// Target: []string{"Succeeded"}, +// Refresh: cdnEndpointStateRefreshFunc(client, resGroup, profileName, name), +// Timeout: 10 * time.Minute, +// } +// if _, err := stateConf.WaitForState(); err != nil { +// return fmt.Errorf("Error waiting for CDN Endpoint (%s) to become available: %s", name, err) +// } +// +// return resourceArmCdnEndpointRead(d, meta) +//} +// +//func resourceArmCdnEndpointRead(d *schema.ResourceData, meta interface{}) error { +// cdnEndpointsClient := meta.(*ArmClient).cdnEndpointsClient +// +// id, err := parseAzureResourceID(d.Id()) +// if err != nil { +// return err +// } +// resGroup := id.ResourceGroup +// name := id.Path["endpoints"] +// profileName := id.Path["profiles"] +// if profileName == "" { +// profileName = id.Path["Profiles"] +// } +// log.Printf("[INFO] Trying to find the AzureRM CDN Endpoint %s (Profile: %s, RG: %s)", name, profileName, resGroup) +// resp, err := cdnEndpointsClient.Get(name, profileName, resGroup) +// if resp.StatusCode == http.StatusNotFound { +// d.SetId("") +// return nil +// } +// if err != nil { +// return fmt.Errorf("Error making Read request on Azure CDN Endpoint %s: %s", name, err) +// } +// +// d.Set("name", resp.Name) +// d.Set("host_name", resp.Properties.HostName) +// d.Set("is_compression_enabled", resp.Properties.IsCompressionEnabled) +// d.Set("is_http_allowed", resp.Properties.IsHTTPAllowed) +// d.Set("is_https_allowed", resp.Properties.IsHTTPSAllowed) +// d.Set("querystring_caching_behaviour", resp.Properties.QueryStringCachingBehavior) +// if resp.Properties.OriginHostHeader != nil && *resp.Properties.OriginHostHeader != "" { +// d.Set("origin_host_header", resp.Properties.OriginHostHeader) +// } +// if resp.Properties.OriginPath != nil && *resp.Properties.OriginPath != "" { +// d.Set("origin_path", resp.Properties.OriginPath) +// } +// if resp.Properties.ContentTypesToCompress != nil && len(*resp.Properties.ContentTypesToCompress) > 0 { +// d.Set("content_types_to_compress", flattenAzureRMCdnEndpointContentTypes(resp.Properties.ContentTypesToCompress)) +// } +// d.Set("origin", flattenAzureRMCdnEndpointOrigin(resp.Properties.Origins)) +// +// flattenAndSetTags(d, resp.Tags) +// +// return nil +//} +// +//func resourceArmCdnEndpointUpdate(d *schema.ResourceData, meta interface{}) error { +// cdnEndpointsClient := meta.(*ArmClient).cdnEndpointsClient +// +// if !d.HasChange("tags") { +// return nil +// } +// +// name := d.Get("name").(string) +// resGroup := d.Get("resource_group_name").(string) +// profileName := d.Get("profile_name").(string) +// http_allowed := d.Get("is_http_allowed").(bool) +// https_allowed := d.Get("is_https_allowed").(bool) +// compression_enabled := d.Get("is_compression_enabled").(bool) +// caching_behaviour := d.Get("querystring_caching_behaviour").(string) +// newTags := d.Get("tags").(map[string]interface{}) +// +// properties := cdn.EndpointPropertiesCreateUpdateParameters{ +// IsHTTPAllowed: &http_allowed, +// IsHTTPSAllowed: &https_allowed, +// IsCompressionEnabled: &compression_enabled, +// QueryStringCachingBehavior: cdn.QueryStringCachingBehavior(caching_behaviour), +// } +// +// if d.HasChange("origin") { +// origins, originsErr := expandAzureRmCdnEndpointOrigins(d) +// if originsErr != nil { +// return fmt.Errorf("Error Building list of CDN Endpoint Origins: %s", originsErr) +// } +// if len(origins) > 0 { +// properties.Origins = &origins +// } +// } +// +// if d.HasChange("origin_host_header") { +// host_header := d.Get("origin_host_header").(string) +// properties.OriginHostHeader = &host_header +// } +// +// if d.HasChange("origin_path") { +// origin_path := d.Get("origin_path").(string) +// properties.OriginPath = &origin_path +// } +// +// if d.HasChange("content_types_to_compress") { +// var content_types []string +// ctypes := d.Get("content_types_to_compress").(*schema.Set).List() +// for _, ct := range ctypes { +// str := ct.(string) +// content_types = append(content_types, str) +// } +// +// properties.ContentTypesToCompress = &content_types +// } +// +// updateProps := cdn.EndpointUpdateParameters{ +// Tags: expandTags(newTags), +// Properties: &properties, +// } +// +// _, err := cdnEndpointsClient.Update(name, updateProps, profileName, resGroup) +// if err != nil { +// return fmt.Errorf("Error issuing Azure ARM update request to update CDN Endpoint %q: %s", name, err) +// } +// +// return resourceArmCdnEndpointRead(d, meta) +//} +// +//func resourceArmCdnEndpointDelete(d *schema.ResourceData, meta interface{}) error { +// client := meta.(*ArmClient).cdnEndpointsClient +// +// id, err := parseAzureResourceID(d.Id()) +// if err != nil { +// return err +// } +// resGroup := id.ResourceGroup +// profileName := id.Path["profiles"] +// if profileName == "" { +// profileName = id.Path["Profiles"] +// } +// name := id.Path["endpoints"] +// +// accResp, err := client.DeleteIfExists(name, profileName, resGroup) +// if err != nil { +// if accResp.StatusCode == http.StatusNotFound { +// return nil +// } +// return fmt.Errorf("Error issuing AzureRM delete request for CDN Endpoint %q: %s", name, err) +// } +// _, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response, http.StatusNotFound) +// if err != nil { +// return fmt.Errorf("Error polling for AzureRM delete request for CDN Endpoint %q: %s", name, err) +// } +// +// return err +//} +// +//func cdnEndpointStateRefreshFunc(client *ArmClient, resourceGroupName string, profileName string, name string) resource.StateRefreshFunc { +// return func() (interface{}, string, error) { +// res, err := client.cdnEndpointsClient.Get(name, profileName, resourceGroupName) +// if err != nil { +// return nil, "", fmt.Errorf("Error issuing read request in cdnEndpointStateRefreshFunc to Azure ARM for CDN Endpoint '%s' (RG: '%s'): %s", name, resourceGroupName, err) +// } +// return res, string(res.Properties.ProvisioningState), nil +// } +//} +// +//func validateCdnEndpointQuerystringCachingBehaviour(v interface{}, k string) (ws []string, errors []error) { +// value := strings.ToLower(v.(string)) +// cachingTypes := map[string]bool{ +// "ignorequerystring": true, +// "bypasscaching": true, +// "usequerystring": true, +// } +// +// if !cachingTypes[value] { +// errors = append(errors, fmt.Errorf("CDN Endpoint querystringCachingBehaviours can only be IgnoreQueryString, BypassCaching or UseQueryString")) +// } +// return +//} +// +//func resourceArmCdnEndpointOriginHash(v interface{}) int { +// var buf bytes.Buffer +// m := v.(map[string]interface{}) +// buf.WriteString(fmt.Sprintf("%s-", m["name"].(string))) +// buf.WriteString(fmt.Sprintf("%s-", m["host_name"].(string))) +// +// return hashcode.String(buf.String()) +//} +// +//func expandAzureRmCdnEndpointOrigins(d *schema.ResourceData) ([]cdn.DeepCreatedOrigin, error) { +// configs := d.Get("origin").(*schema.Set).List() +// origins := make([]cdn.DeepCreatedOrigin, 0, len(configs)) +// +// for _, configRaw := range configs { +// data := configRaw.(map[string]interface{}) +// +// host_name := data["host_name"].(string) +// +// properties := cdn.DeepCreatedOriginProperties{ +// HostName: &host_name, +// } +// +// if v, ok := data["https_port"]; ok { +// https_port := v.(int) +// properties.HTTPSPort = &https_port +// +// } +// +// if v, ok := data["http_port"]; ok { +// http_port := v.(int) +// properties.HTTPPort = &http_port +// } +// +// name := data["name"].(string) +// +// origin := cdn.DeepCreatedOrigin{ +// Name: &name, +// Properties: &properties, +// } +// +// origins = append(origins, origin) +// } +// +// return origins, nil +//} +// +//func flattenAzureRMCdnEndpointOrigin(list *[]cdn.DeepCreatedOrigin) []map[string]interface{} { +// result := make([]map[string]interface{}, 0, len(*list)) +// for _, i := range *list { +// l := map[string]interface{}{ +// "name": *i.Name, +// "host_name": *i.Properties.HostName, +// } +// +// if i.Properties.HTTPPort != nil { +// l["http_port"] = *i.Properties.HTTPPort +// } +// if i.Properties.HTTPSPort != nil { +// l["https_port"] = *i.Properties.HTTPSPort +// } +// result = append(result, l) +// } +// return result +//} +// +//func flattenAzureRMCdnEndpointContentTypes(list *[]string) []interface{} { +// vs := make([]interface{}, 0, len(*list)) +// for _, v := range *list { +// vs = append(vs, v) +// } +// return vs +//} diff --git a/builtin/providers/azurerm/resource_arm_cdn_endpoint_test.go b/builtin/providers/azurerm/resource_arm_cdn_endpoint_test.go index f7a7d86ab85f..bd2a93fc5fbc 100644 --- a/builtin/providers/azurerm/resource_arm_cdn_endpoint_test.go +++ b/builtin/providers/azurerm/resource_arm_cdn_endpoint_test.go @@ -1,215 +1,215 @@ 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 TestAccAzureRMCdnEndpoint_basic(t *testing.T) { - - ri := acctest.RandInt() - config := fmt.Sprintf(testAccAzureRMCdnEndpoint_basic, ri, ri, ri) - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMCdnEndpointDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: config, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMCdnEndpointExists("azurerm_cdn_endpoint.test"), - ), - }, - }, - }) -} - -func TestAccAzureRMCdnEndpoints_withTags(t *testing.T) { - - ri := acctest.RandInt() - preConfig := fmt.Sprintf(testAccAzureRMCdnEndpoint_withTags, ri, ri, ri) - postConfig := fmt.Sprintf(testAccAzureRMCdnEndpoint_withTagsUpdate, ri, ri, ri) - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMCdnEndpointDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: preConfig, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMCdnEndpointExists("azurerm_cdn_endpoint.test"), - resource.TestCheckResourceAttr( - "azurerm_cdn_endpoint.test", "tags.#", "2"), - resource.TestCheckResourceAttr( - "azurerm_cdn_endpoint.test", "tags.environment", "Production"), - resource.TestCheckResourceAttr( - "azurerm_cdn_endpoint.test", "tags.cost_center", "MSFT"), - ), - }, - - resource.TestStep{ - Config: postConfig, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMCdnEndpointExists("azurerm_cdn_endpoint.test"), - resource.TestCheckResourceAttr( - "azurerm_cdn_endpoint.test", "tags.#", "1"), - resource.TestCheckResourceAttr( - "azurerm_cdn_endpoint.test", "tags.environment", "staging"), - ), - }, - }, - }) -} - -func testCheckAzureRMCdnEndpointExists(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) - } - - name := rs.Primary.Attributes["name"] - profileName := rs.Primary.Attributes["profile_name"] - resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] - if !hasResourceGroup { - return fmt.Errorf("Bad: no resource group found in state for cdn endpoint: %s", name) - } - - conn := testAccProvider.Meta().(*ArmClient).cdnEndpointsClient - - resp, err := conn.Get(name, profileName, resourceGroup) - if err != nil { - return fmt.Errorf("Bad: Get on cdnEndpointsClient: %s", err) - } - - if resp.StatusCode == http.StatusNotFound { - return fmt.Errorf("Bad: CDN Endpoint %q (resource group: %q) does not exist", name, resourceGroup) - } - - return nil - } -} - -func testCheckAzureRMCdnEndpointDestroy(s *terraform.State) error { - conn := testAccProvider.Meta().(*ArmClient).cdnEndpointsClient - - for _, rs := range s.RootModule().Resources { - if rs.Type != "azurerm_cdn_endpoint" { - continue - } - - name := rs.Primary.Attributes["name"] - resourceGroup := rs.Primary.Attributes["resource_group_name"] - profileName := rs.Primary.Attributes["profile_name"] - - resp, err := conn.Get(name, profileName, resourceGroup) - - if err != nil { - return nil - } - - if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("CDN Endpoint still exists:\n%#v", resp.Properties) - } - } - - return nil -} - -var testAccAzureRMCdnEndpoint_basic = ` -resource "azurerm_resource_group" "test" { - name = "acctestrg-%d" - location = "West US" -} -resource "azurerm_cdn_profile" "test" { - name = "acctestcdnprof%d" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - sku = "Standard" -} - -resource "azurerm_cdn_endpoint" "test" { - name = "acctestcdnend%d" - profile_name = "${azurerm_cdn_profile.test.name}" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - - origin { - name = "acceptanceTestCdnOrigin1" - host_name = "www.example.com" - https_port = 443 - http_port = 80 - } -} -` - -var testAccAzureRMCdnEndpoint_withTags = ` -resource "azurerm_resource_group" "test" { - name = "acctestrg-%d" - location = "West US" -} -resource "azurerm_cdn_profile" "test" { - name = "acctestcdnprof%d" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - sku = "Standard" -} - -resource "azurerm_cdn_endpoint" "test" { - name = "acctestcdnend%d" - profile_name = "${azurerm_cdn_profile.test.name}" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - - origin { - name = "acceptanceTestCdnOrigin2" - host_name = "www.example.com" - https_port = 443 - http_port = 80 - } - - tags { - environment = "Production" - cost_center = "MSFT" - } -} -` - -var testAccAzureRMCdnEndpoint_withTagsUpdate = ` -resource "azurerm_resource_group" "test" { - name = "acctestrg-%d" - location = "West US" -} -resource "azurerm_cdn_profile" "test" { - name = "acctestcdnprof%d" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - sku = "Standard" -} - -resource "azurerm_cdn_endpoint" "test" { - name = "acctestcdnend%d" - profile_name = "${azurerm_cdn_profile.test.name}" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - - origin { - name = "acceptanceTestCdnOrigin2" - host_name = "www.example.com" - https_port = 443 - http_port = 80 - } - - tags { - environment = "staging" - } -} -` +//import ( +// "fmt" +// "net/http" +// "testing" +// +// "github.com/hashicorp/terraform/helper/acctest" +// "github.com/hashicorp/terraform/helper/resource" +// "github.com/hashicorp/terraform/terraform" +//) +// +//func TestAccAzureRMCdnEndpoint_basic(t *testing.T) { +// +// ri := acctest.RandInt() +// config := fmt.Sprintf(testAccAzureRMCdnEndpoint_basic, ri, ri, ri) +// +// resource.Test(t, resource.TestCase{ +// PreCheck: func() { testAccPreCheck(t) }, +// Providers: testAccProviders, +// CheckDestroy: testCheckAzureRMCdnEndpointDestroy, +// Steps: []resource.TestStep{ +// resource.TestStep{ +// Config: config, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMCdnEndpointExists("azurerm_cdn_endpoint.test"), +// ), +// }, +// }, +// }) +//} +// +//func TestAccAzureRMCdnEndpoints_withTags(t *testing.T) { +// +// ri := acctest.RandInt() +// preConfig := fmt.Sprintf(testAccAzureRMCdnEndpoint_withTags, ri, ri, ri) +// postConfig := fmt.Sprintf(testAccAzureRMCdnEndpoint_withTagsUpdate, ri, ri, ri) +// +// resource.Test(t, resource.TestCase{ +// PreCheck: func() { testAccPreCheck(t) }, +// Providers: testAccProviders, +// CheckDestroy: testCheckAzureRMCdnEndpointDestroy, +// Steps: []resource.TestStep{ +// resource.TestStep{ +// Config: preConfig, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMCdnEndpointExists("azurerm_cdn_endpoint.test"), +// resource.TestCheckResourceAttr( +// "azurerm_cdn_endpoint.test", "tags.#", "2"), +// resource.TestCheckResourceAttr( +// "azurerm_cdn_endpoint.test", "tags.environment", "Production"), +// resource.TestCheckResourceAttr( +// "azurerm_cdn_endpoint.test", "tags.cost_center", "MSFT"), +// ), +// }, +// +// resource.TestStep{ +// Config: postConfig, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMCdnEndpointExists("azurerm_cdn_endpoint.test"), +// resource.TestCheckResourceAttr( +// "azurerm_cdn_endpoint.test", "tags.#", "1"), +// resource.TestCheckResourceAttr( +// "azurerm_cdn_endpoint.test", "tags.environment", "staging"), +// ), +// }, +// }, +// }) +//} +// +//func testCheckAzureRMCdnEndpointExists(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) +// } +// +// name := rs.Primary.Attributes["name"] +// profileName := rs.Primary.Attributes["profile_name"] +// resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] +// if !hasResourceGroup { +// return fmt.Errorf("Bad: no resource group found in state for cdn endpoint: %s", name) +// } +// +// conn := testAccProvider.Meta().(*ArmClient).cdnEndpointsClient +// +// resp, err := conn.Get(name, profileName, resourceGroup) +// if err != nil { +// return fmt.Errorf("Bad: Get on cdnEndpointsClient: %s", err) +// } +// +// if resp.StatusCode == http.StatusNotFound { +// return fmt.Errorf("Bad: CDN Endpoint %q (resource group: %q) does not exist", name, resourceGroup) +// } +// +// return nil +// } +//} +// +//func testCheckAzureRMCdnEndpointDestroy(s *terraform.State) error { +// conn := testAccProvider.Meta().(*ArmClient).cdnEndpointsClient +// +// for _, rs := range s.RootModule().Resources { +// if rs.Type != "azurerm_cdn_endpoint" { +// continue +// } +// +// name := rs.Primary.Attributes["name"] +// resourceGroup := rs.Primary.Attributes["resource_group_name"] +// profileName := rs.Primary.Attributes["profile_name"] +// +// resp, err := conn.Get(name, profileName, resourceGroup) +// +// if err != nil { +// return nil +// } +// +// if resp.StatusCode != http.StatusNotFound { +// return fmt.Errorf("CDN Endpoint still exists:\n%#v", resp.Properties) +// } +// } +// +// return nil +//} +// +//var testAccAzureRMCdnEndpoint_basic = ` +//resource "azurerm_resource_group" "test" { +// name = "acctestrg-%d" +// location = "West US" +//} +//resource "azurerm_cdn_profile" "test" { +// name = "acctestcdnprof%d" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// sku = "Standard" +//} +// +//resource "azurerm_cdn_endpoint" "test" { +// name = "acctestcdnend%d" +// profile_name = "${azurerm_cdn_profile.test.name}" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// +// origin { +// name = "acceptanceTestCdnOrigin1" +// host_name = "www.example.com" +// https_port = 443 +// http_port = 80 +// } +//} +//` +// +//var testAccAzureRMCdnEndpoint_withTags = ` +//resource "azurerm_resource_group" "test" { +// name = "acctestrg-%d" +// location = "West US" +//} +//resource "azurerm_cdn_profile" "test" { +// name = "acctestcdnprof%d" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// sku = "Standard" +//} +// +//resource "azurerm_cdn_endpoint" "test" { +// name = "acctestcdnend%d" +// profile_name = "${azurerm_cdn_profile.test.name}" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// +// origin { +// name = "acceptanceTestCdnOrigin2" +// host_name = "www.example.com" +// https_port = 443 +// http_port = 80 +// } +// +// tags { +// environment = "Production" +// cost_center = "MSFT" +// } +//} +//` +// +//var testAccAzureRMCdnEndpoint_withTagsUpdate = ` +//resource "azurerm_resource_group" "test" { +// name = "acctestrg-%d" +// location = "West US" +//} +//resource "azurerm_cdn_profile" "test" { +// name = "acctestcdnprof%d" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// sku = "Standard" +//} +// +//resource "azurerm_cdn_endpoint" "test" { +// name = "acctestcdnend%d" +// profile_name = "${azurerm_cdn_profile.test.name}" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// +// origin { +// name = "acceptanceTestCdnOrigin2" +// host_name = "www.example.com" +// https_port = 443 +// http_port = 80 +// } +// +// tags { +// environment = "staging" +// } +//} +//` diff --git a/builtin/providers/azurerm/resource_arm_cdn_profile.go b/builtin/providers/azurerm/resource_arm_cdn_profile.go index 49681e2eff41..c3044b94090f 100644 --- a/builtin/providers/azurerm/resource_arm_cdn_profile.go +++ b/builtin/providers/azurerm/resource_arm_cdn_profile.go @@ -1,186 +1,186 @@ package azurerm -import ( - "fmt" - "log" - "net/http" - "strings" - "time" - - "github.com/Azure/azure-sdk-for-go/arm/cdn" - "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/helper/schema" -) - -func resourceArmCdnProfile() *schema.Resource { - return &schema.Resource{ - Create: resourceArmCdnProfileCreate, - Read: resourceArmCdnProfileRead, - Update: resourceArmCdnProfileUpdate, - Delete: resourceArmCdnProfileDelete, - - Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - - "location": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - StateFunc: azureRMNormalizeLocation, - }, - - "resource_group_name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - - "sku": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validateCdnProfileSku, - }, - - "tags": tagsSchema(), - }, - } -} - -func resourceArmCdnProfileCreate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient) - cdnProfilesClient := client.cdnProfilesClient - - log.Printf("[INFO] preparing arguments for Azure ARM CDN Profile creation.") - - name := d.Get("name").(string) - location := d.Get("location").(string) - resGroup := d.Get("resource_group_name").(string) - sku := d.Get("sku").(string) - tags := d.Get("tags").(map[string]interface{}) - - properties := cdn.ProfilePropertiesCreateParameters{ - Sku: &cdn.Sku{ - Name: cdn.SkuName(sku), - }, - } - - cdnProfile := cdn.ProfileCreateParameters{ - Location: &location, - Properties: &properties, - Tags: expandTags(tags), - } - - resp, err := cdnProfilesClient.Create(name, cdnProfile, resGroup) - if err != nil { - return err - } - - d.SetId(*resp.ID) - - log.Printf("[DEBUG] Waiting for CDN Profile (%s) to become available", name) - stateConf := &resource.StateChangeConf{ - Pending: []string{"Accepted", "Updating", "Creating"}, - Target: []string{"Succeeded"}, - Refresh: cdnProfileStateRefreshFunc(client, resGroup, name), - Timeout: 10 * time.Minute, - } - if _, err := stateConf.WaitForState(); err != nil { - return fmt.Errorf("Error waiting for CDN Profile (%s) to become available: %s", name, err) - } - - return resourceArmCdnProfileRead(d, meta) -} - -func resourceArmCdnProfileRead(d *schema.ResourceData, meta interface{}) error { - cdnProfilesClient := meta.(*ArmClient).cdnProfilesClient - - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - resGroup := id.ResourceGroup - name := id.Path["Profiles"] - - resp, err := cdnProfilesClient.Get(name, resGroup) - if resp.StatusCode == http.StatusNotFound { - d.SetId("") - return nil - } - if err != nil { - return fmt.Errorf("Error making Read request on Azure CDN Profile %s: %s", name, err) - } - - if resp.Properties != nil && resp.Properties.Sku != nil { - d.Set("sku", string(resp.Properties.Sku.Name)) - } - - flattenAndSetTags(d, resp.Tags) - - return nil -} - -func resourceArmCdnProfileUpdate(d *schema.ResourceData, meta interface{}) error { - cdnProfilesClient := meta.(*ArmClient).cdnProfilesClient - - if !d.HasChange("tags") { - return nil - } - - name := d.Get("name").(string) - resGroup := d.Get("resource_group_name").(string) - newTags := d.Get("tags").(map[string]interface{}) - - props := cdn.ProfileUpdateParameters{ - Tags: expandTags(newTags), - } - - _, err := cdnProfilesClient.Update(name, props, resGroup) - if err != nil { - return fmt.Errorf("Error issuing Azure ARM update request to update CDN Profile %q: %s", name, err) - } - - return resourceArmCdnProfileRead(d, meta) -} - -func resourceArmCdnProfileDelete(d *schema.ResourceData, meta interface{}) error { - cdnProfilesClient := meta.(*ArmClient).cdnProfilesClient - - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - resGroup := id.ResourceGroup - name := id.Path["Profiles"] - - _, err = cdnProfilesClient.DeleteIfExists(name, resGroup) - - return err -} - -func cdnProfileStateRefreshFunc(client *ArmClient, resourceGroupName string, cdnProfileName string) resource.StateRefreshFunc { - return func() (interface{}, string, error) { - res, err := client.cdnProfilesClient.Get(cdnProfileName, resourceGroupName) - if err != nil { - return nil, "", fmt.Errorf("Error issuing read request in cdnProfileStateRefreshFunc to Azure ARM for CND Profile '%s' (RG: '%s'): %s", cdnProfileName, resourceGroupName, err) - } - return res, string(res.Properties.ProvisioningState), nil - } -} - -func validateCdnProfileSku(v interface{}, k string) (ws []string, errors []error) { - value := strings.ToLower(v.(string)) - skus := map[string]bool{ - "standard": true, - "premium": true, - } - - if !skus[value] { - errors = append(errors, fmt.Errorf("CDN Profile SKU can only be Standard or Premium")) - } - return -} +//import ( +// "fmt" +// "log" +// "net/http" +// "strings" +// "time" +// +// "github.com/Azure/azure-sdk-for-go/arm/cdn" +// "github.com/hashicorp/terraform/helper/resource" +// "github.com/hashicorp/terraform/helper/schema" +//) +// +//func resourceArmCdnProfile() *schema.Resource { +// return &schema.Resource{ +// Create: resourceArmCdnProfileCreate, +// Read: resourceArmCdnProfileRead, +// Update: resourceArmCdnProfileUpdate, +// Delete: resourceArmCdnProfileDelete, +// +// Schema: map[string]*schema.Schema{ +// "name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// }, +// +// "location": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// StateFunc: azureRMNormalizeLocation, +// }, +// +// "resource_group_name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// }, +// +// "sku": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// ValidateFunc: validateCdnProfileSku, +// }, +// +// "tags": tagsSchema(), +// }, +// } +//} +// +//func resourceArmCdnProfileCreate(d *schema.ResourceData, meta interface{}) error { +// client := meta.(*ArmClient) +// cdnProfilesClient := client.cdnProfilesClient +// +// log.Printf("[INFO] preparing arguments for Azure ARM CDN Profile creation.") +// +// name := d.Get("name").(string) +// location := d.Get("location").(string) +// resGroup := d.Get("resource_group_name").(string) +// sku := d.Get("sku").(string) +// tags := d.Get("tags").(map[string]interface{}) +// +// properties := cdn.ProfilePropertiesCreateParameters{ +// Sku: &cdn.Sku{ +// Name: cdn.SkuName(sku), +// }, +// } +// +// cdnProfile := cdn.ProfileCreateParameters{ +// Location: &location, +// Properties: &properties, +// Tags: expandTags(tags), +// } +// +// resp, err := cdnProfilesClient.Create(name, cdnProfile, resGroup) +// if err != nil { +// return err +// } +// +// d.SetId(*resp.ID) +// +// log.Printf("[DEBUG] Waiting for CDN Profile (%s) to become available", name) +// stateConf := &resource.StateChangeConf{ +// Pending: []string{"Accepted", "Updating", "Creating"}, +// Target: []string{"Succeeded"}, +// Refresh: cdnProfileStateRefreshFunc(client, resGroup, name), +// Timeout: 10 * time.Minute, +// } +// if _, err := stateConf.WaitForState(); err != nil { +// return fmt.Errorf("Error waiting for CDN Profile (%s) to become available: %s", name, err) +// } +// +// return resourceArmCdnProfileRead(d, meta) +//} +// +//func resourceArmCdnProfileRead(d *schema.ResourceData, meta interface{}) error { +// cdnProfilesClient := meta.(*ArmClient).cdnProfilesClient +// +// id, err := parseAzureResourceID(d.Id()) +// if err != nil { +// return err +// } +// resGroup := id.ResourceGroup +// name := id.Path["Profiles"] +// +// resp, err := cdnProfilesClient.Get(name, resGroup) +// if resp.StatusCode == http.StatusNotFound { +// d.SetId("") +// return nil +// } +// if err != nil { +// return fmt.Errorf("Error making Read request on Azure CDN Profile %s: %s", name, err) +// } +// +// if resp.Properties != nil && resp.Properties.Sku != nil { +// d.Set("sku", string(resp.Properties.Sku.Name)) +// } +// +// flattenAndSetTags(d, resp.Tags) +// +// return nil +//} +// +//func resourceArmCdnProfileUpdate(d *schema.ResourceData, meta interface{}) error { +// cdnProfilesClient := meta.(*ArmClient).cdnProfilesClient +// +// if !d.HasChange("tags") { +// return nil +// } +// +// name := d.Get("name").(string) +// resGroup := d.Get("resource_group_name").(string) +// newTags := d.Get("tags").(map[string]interface{}) +// +// props := cdn.ProfileUpdateParameters{ +// Tags: expandTags(newTags), +// } +// +// _, err := cdnProfilesClient.Update(name, props, resGroup) +// if err != nil { +// return fmt.Errorf("Error issuing Azure ARM update request to update CDN Profile %q: %s", name, err) +// } +// +// return resourceArmCdnProfileRead(d, meta) +//} +// +//func resourceArmCdnProfileDelete(d *schema.ResourceData, meta interface{}) error { +// cdnProfilesClient := meta.(*ArmClient).cdnProfilesClient +// +// id, err := parseAzureResourceID(d.Id()) +// if err != nil { +// return err +// } +// resGroup := id.ResourceGroup +// name := id.Path["Profiles"] +// +// _, err = cdnProfilesClient.DeleteIfExists(name, resGroup) +// +// return err +//} +// +//func cdnProfileStateRefreshFunc(client *ArmClient, resourceGroupName string, cdnProfileName string) resource.StateRefreshFunc { +// return func() (interface{}, string, error) { +// res, err := client.cdnProfilesClient.Get(cdnProfileName, resourceGroupName) +// if err != nil { +// return nil, "", fmt.Errorf("Error issuing read request in cdnProfileStateRefreshFunc to Azure ARM for CND Profile '%s' (RG: '%s'): %s", cdnProfileName, resourceGroupName, err) +// } +// return res, string(res.Properties.ProvisioningState), nil +// } +//} +// +//func validateCdnProfileSku(v interface{}, k string) (ws []string, errors []error) { +// value := strings.ToLower(v.(string)) +// skus := map[string]bool{ +// "standard": true, +// "premium": true, +// } +// +// if !skus[value] { +// errors = append(errors, fmt.Errorf("CDN Profile SKU can only be Standard or Premium")) +// } +// return +//} diff --git a/builtin/providers/azurerm/resource_arm_cdn_profile_test.go b/builtin/providers/azurerm/resource_arm_cdn_profile_test.go index 82582959b6ff..c72c560b289e 100644 --- a/builtin/providers/azurerm/resource_arm_cdn_profile_test.go +++ b/builtin/providers/azurerm/resource_arm_cdn_profile_test.go @@ -1,207 +1,207 @@ 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 TestResourceAzureRMCdnProfileSKU_validation(t *testing.T) { - cases := []struct { - Value string - ErrCount int - }{ - { - Value: "Random", - ErrCount: 1, - }, - { - Value: "Standard", - ErrCount: 0, - }, - { - Value: "Premium", - ErrCount: 0, - }, - { - Value: "STANDARD", - ErrCount: 0, - }, - { - Value: "PREMIUM", - ErrCount: 0, - }, - } - - for _, tc := range cases { - _, errors := validateCdnProfileSku(tc.Value, "azurerm_cdn_profile") - - if len(errors) != tc.ErrCount { - t.Fatalf("Expected the Azure RM CDN Profile SKU to trigger a validation error") - } - } -} - -func TestAccAzureRMCdnProfile_basic(t *testing.T) { - - ri := acctest.RandInt() - config := fmt.Sprintf(testAccAzureRMCdnProfile_basic, ri, ri) - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMCdnProfileDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: config, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMCdnProfileExists("azurerm_cdn_profile.test"), - ), - }, - }, - }) -} - -func TestAccAzureRMCdnProfile_withTags(t *testing.T) { - - ri := acctest.RandInt() - preConfig := fmt.Sprintf(testAccAzureRMCdnProfile_withTags, ri, ri) - postConfig := fmt.Sprintf(testAccAzureRMCdnProfile_withTagsUpdate, ri, ri) - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMCdnProfileDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: preConfig, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMCdnProfileExists("azurerm_cdn_profile.test"), - resource.TestCheckResourceAttr( - "azurerm_cdn_profile.test", "tags.#", "2"), - resource.TestCheckResourceAttr( - "azurerm_cdn_profile.test", "tags.environment", "Production"), - resource.TestCheckResourceAttr( - "azurerm_cdn_profile.test", "tags.cost_center", "MSFT"), - ), - }, - - resource.TestStep{ - Config: postConfig, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMCdnProfileExists("azurerm_cdn_profile.test"), - resource.TestCheckResourceAttr( - "azurerm_cdn_profile.test", "tags.#", "1"), - resource.TestCheckResourceAttr( - "azurerm_cdn_profile.test", "tags.environment", "staging"), - ), - }, - }, - }) -} - -func testCheckAzureRMCdnProfileExists(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) - } - - name := rs.Primary.Attributes["name"] - resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] - if !hasResourceGroup { - return fmt.Errorf("Bad: no resource group found in state for cdn profile: %s", name) - } - - conn := testAccProvider.Meta().(*ArmClient).cdnProfilesClient - - resp, err := conn.Get(name, resourceGroup) - if err != nil { - return fmt.Errorf("Bad: Get on cdnProfilesClient: %s", err) - } - - if resp.StatusCode == http.StatusNotFound { - return fmt.Errorf("Bad: CDN Profile %q (resource group: %q) does not exist", name, resourceGroup) - } - - return nil - } -} - -func testCheckAzureRMCdnProfileDestroy(s *terraform.State) error { - conn := testAccProvider.Meta().(*ArmClient).cdnProfilesClient - - for _, rs := range s.RootModule().Resources { - if rs.Type != "azurerm_cdn_profile" { - continue - } - - name := rs.Primary.Attributes["name"] - resourceGroup := rs.Primary.Attributes["resource_group_name"] - - resp, err := conn.Get(name, resourceGroup) - - if err != nil { - return nil - } - - if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("CDN Profile still exists:\n%#v", resp.Properties) - } - } - - return nil -} - -var testAccAzureRMCdnProfile_basic = ` -resource "azurerm_resource_group" "test" { - name = "acctestrg-%d" - location = "West US" -} -resource "azurerm_cdn_profile" "test" { - name = "acctestcdnprof%d" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - sku = "Standard" -} -` - -var testAccAzureRMCdnProfile_withTags = ` -resource "azurerm_resource_group" "test" { - name = "acctestrg-%d" - location = "West US" -} -resource "azurerm_cdn_profile" "test" { - name = "acctestcdnprof%d" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - sku = "Standard" - - tags { - environment = "Production" - cost_center = "MSFT" - } -} -` - -var testAccAzureRMCdnProfile_withTagsUpdate = ` -resource "azurerm_resource_group" "test" { - name = "acctestrg-%d" - location = "West US" -} -resource "azurerm_cdn_profile" "test" { - name = "acctestcdnprof%d" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - sku = "Standard" - - tags { - environment = "staging" - } -} -` +//import ( +// "fmt" +// "net/http" +// "testing" +// +// "github.com/hashicorp/terraform/helper/acctest" +// "github.com/hashicorp/terraform/helper/resource" +// "github.com/hashicorp/terraform/terraform" +//) +// +//func TestResourceAzureRMCdnProfileSKU_validation(t *testing.T) { +// cases := []struct { +// Value string +// ErrCount int +// }{ +// { +// Value: "Random", +// ErrCount: 1, +// }, +// { +// Value: "Standard", +// ErrCount: 0, +// }, +// { +// Value: "Premium", +// ErrCount: 0, +// }, +// { +// Value: "STANDARD", +// ErrCount: 0, +// }, +// { +// Value: "PREMIUM", +// ErrCount: 0, +// }, +// } +// +// for _, tc := range cases { +// _, errors := validateCdnProfileSku(tc.Value, "azurerm_cdn_profile") +// +// if len(errors) != tc.ErrCount { +// t.Fatalf("Expected the Azure RM CDN Profile SKU to trigger a validation error") +// } +// } +//} +// +//func TestAccAzureRMCdnProfile_basic(t *testing.T) { +// +// ri := acctest.RandInt() +// config := fmt.Sprintf(testAccAzureRMCdnProfile_basic, ri, ri) +// +// resource.Test(t, resource.TestCase{ +// PreCheck: func() { testAccPreCheck(t) }, +// Providers: testAccProviders, +// CheckDestroy: testCheckAzureRMCdnProfileDestroy, +// Steps: []resource.TestStep{ +// resource.TestStep{ +// Config: config, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMCdnProfileExists("azurerm_cdn_profile.test"), +// ), +// }, +// }, +// }) +//} +// +//func TestAccAzureRMCdnProfile_withTags(t *testing.T) { +// +// ri := acctest.RandInt() +// preConfig := fmt.Sprintf(testAccAzureRMCdnProfile_withTags, ri, ri) +// postConfig := fmt.Sprintf(testAccAzureRMCdnProfile_withTagsUpdate, ri, ri) +// +// resource.Test(t, resource.TestCase{ +// PreCheck: func() { testAccPreCheck(t) }, +// Providers: testAccProviders, +// CheckDestroy: testCheckAzureRMCdnProfileDestroy, +// Steps: []resource.TestStep{ +// resource.TestStep{ +// Config: preConfig, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMCdnProfileExists("azurerm_cdn_profile.test"), +// resource.TestCheckResourceAttr( +// "azurerm_cdn_profile.test", "tags.#", "2"), +// resource.TestCheckResourceAttr( +// "azurerm_cdn_profile.test", "tags.environment", "Production"), +// resource.TestCheckResourceAttr( +// "azurerm_cdn_profile.test", "tags.cost_center", "MSFT"), +// ), +// }, +// +// resource.TestStep{ +// Config: postConfig, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMCdnProfileExists("azurerm_cdn_profile.test"), +// resource.TestCheckResourceAttr( +// "azurerm_cdn_profile.test", "tags.#", "1"), +// resource.TestCheckResourceAttr( +// "azurerm_cdn_profile.test", "tags.environment", "staging"), +// ), +// }, +// }, +// }) +//} +// +//func testCheckAzureRMCdnProfileExists(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) +// } +// +// name := rs.Primary.Attributes["name"] +// resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] +// if !hasResourceGroup { +// return fmt.Errorf("Bad: no resource group found in state for cdn profile: %s", name) +// } +// +// conn := testAccProvider.Meta().(*ArmClient).cdnProfilesClient +// +// resp, err := conn.Get(name, resourceGroup) +// if err != nil { +// return fmt.Errorf("Bad: Get on cdnProfilesClient: %s", err) +// } +// +// if resp.StatusCode == http.StatusNotFound { +// return fmt.Errorf("Bad: CDN Profile %q (resource group: %q) does not exist", name, resourceGroup) +// } +// +// return nil +// } +//} +// +//func testCheckAzureRMCdnProfileDestroy(s *terraform.State) error { +// conn := testAccProvider.Meta().(*ArmClient).cdnProfilesClient +// +// for _, rs := range s.RootModule().Resources { +// if rs.Type != "azurerm_cdn_profile" { +// continue +// } +// +// name := rs.Primary.Attributes["name"] +// resourceGroup := rs.Primary.Attributes["resource_group_name"] +// +// resp, err := conn.Get(name, resourceGroup) +// +// if err != nil { +// return nil +// } +// +// if resp.StatusCode != http.StatusNotFound { +// return fmt.Errorf("CDN Profile still exists:\n%#v", resp.Properties) +// } +// } +// +// return nil +//} +// +//var testAccAzureRMCdnProfile_basic = ` +//resource "azurerm_resource_group" "test" { +// name = "acctestrg-%d" +// location = "West US" +//} +//resource "azurerm_cdn_profile" "test" { +// name = "acctestcdnprof%d" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// sku = "Standard" +//} +//` +// +//var testAccAzureRMCdnProfile_withTags = ` +//resource "azurerm_resource_group" "test" { +// name = "acctestrg-%d" +// location = "West US" +//} +//resource "azurerm_cdn_profile" "test" { +// name = "acctestcdnprof%d" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// sku = "Standard" +// +// tags { +// environment = "Production" +// cost_center = "MSFT" +// } +//} +//` +// +//var testAccAzureRMCdnProfile_withTagsUpdate = ` +//resource "azurerm_resource_group" "test" { +// name = "acctestrg-%d" +// location = "West US" +//} +//resource "azurerm_cdn_profile" "test" { +// name = "acctestcdnprof%d" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// sku = "Standard" +// +// tags { +// environment = "staging" +// } +//} +//` diff --git a/builtin/providers/azurerm/resource_arm_local_network_gateway.go b/builtin/providers/azurerm/resource_arm_local_network_gateway.go index ae91d665fc58..9eeda5070862 100644 --- a/builtin/providers/azurerm/resource_arm_local_network_gateway.go +++ b/builtin/providers/azurerm/resource_arm_local_network_gateway.go @@ -1,136 +1,136 @@ package azurerm -import ( - "fmt" - - "github.com/Azure/azure-sdk-for-go/arm/network" - "github.com/Azure/azure-sdk-for-go/core/http" - "github.com/hashicorp/terraform/helper/schema" -) - -func resourceArmLocalNetworkGateway() *schema.Resource { - return &schema.Resource{ - Create: resourceArmLocalNetworkGatewayCreate, - Read: resourceArmLocalNetworkGatewayRead, - Update: resourceArmLocalNetworkGatewayCreate, - Delete: resourceArmLocalNetworkGatewayDelete, - - Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - - "location": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - ForceNew: true, - StateFunc: azureRMNormalizeLocation, - }, - - "resource_group_name": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - ForceNew: true, - }, - - "gateway_address": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - - "address_space": &schema.Schema{ - Type: schema.TypeList, - Required: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - }, - } -} - -func resourceArmLocalNetworkGatewayCreate(d *schema.ResourceData, meta interface{}) error { - lnetClient := meta.(*ArmClient).localNetConnClient - - name := d.Get("name").(string) - location := d.Get("location").(string) - resGroup := d.Get("resource_group_name").(string) - ipAddress := d.Get("gateway_address").(string) - - // fetch the 'address_space_prefixes: - prefixes := []string{} - for _, pref := range d.Get("address_space").([]interface{}) { - prefixes = append(prefixes, pref.(string)) - } - - resp, err := lnetClient.CreateOrUpdate(resGroup, name, network.LocalNetworkGateway{ - Name: &name, - Location: &location, - Properties: &network.LocalNetworkGatewayPropertiesFormat{ - LocalNetworkAddressSpace: &network.AddressSpace{ - AddressPrefixes: &prefixes, - }, - GatewayIPAddress: &ipAddress, - }, - }) - if err != nil { - return fmt.Errorf("Error creating Azure ARM Local Network Gateway '%s': %s", name, err) - } - - d.SetId(*resp.ID) - - return resourceArmLocalNetworkGatewayRead(d, meta) -} - -// resourceArmLocalNetworkGatewayRead goes ahead and reads the state of the corresponding ARM local network gateway. -func resourceArmLocalNetworkGatewayRead(d *schema.ResourceData, meta interface{}) error { - lnetClient := meta.(*ArmClient).localNetConnClient - - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - name := id.Path["localNetworkGateways"] - resGroup := id.ResourceGroup - - resp, err := lnetClient.Get(resGroup, name) - if err != nil { - if resp.StatusCode == http.StatusNotFound { - d.SetId("") - return nil - } - - return fmt.Errorf("Error reading the state of Azure ARM local network gateway '%s': %s", name, err) - } - - d.Set("gateway_address", resp.Properties.GatewayIPAddress) - - prefs := []string{} - if ps := *resp.Properties.LocalNetworkAddressSpace.AddressPrefixes; ps != nil { - prefs = ps - } - d.Set("address_space", prefs) - - return nil -} - -// resourceArmLocalNetworkGatewayDelete deletes the specified ARM local network gateway. -func resourceArmLocalNetworkGatewayDelete(d *schema.ResourceData, meta interface{}) error { - lnetClient := meta.(*ArmClient).localNetConnClient - - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - name := id.Path["localNetworkGateways"] - resGroup := id.ResourceGroup - - _, err = lnetClient.Delete(resGroup, name) - if err != nil { - return fmt.Errorf("Error issuing Azure ARM delete request of local network gateway '%s': %s", name, err) - } - - return nil -} +//import ( +// "fmt" +// +// "github.com/Azure/azure-sdk-for-go/arm/network" +// "github.com/Azure/azure-sdk-for-go/core/http" +// "github.com/hashicorp/terraform/helper/schema" +//) +// +//func resourceArmLocalNetworkGateway() *schema.Resource { +// return &schema.Resource{ +// Create: resourceArmLocalNetworkGatewayCreate, +// Read: resourceArmLocalNetworkGatewayRead, +// Update: resourceArmLocalNetworkGatewayCreate, +// Delete: resourceArmLocalNetworkGatewayDelete, +// +// Schema: map[string]*schema.Schema{ +// "name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// }, +// +// "location": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// ForceNew: true, +// StateFunc: azureRMNormalizeLocation, +// }, +// +// "resource_group_name": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// ForceNew: true, +// }, +// +// "gateway_address": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "address_space": &schema.Schema{ +// Type: schema.TypeList, +// Required: true, +// Elem: &schema.Schema{ +// Type: schema.TypeString, +// }, +// }, +// }, +// } +//} +// +//func resourceArmLocalNetworkGatewayCreate(d *schema.ResourceData, meta interface{}) error { +// lnetClient := meta.(*ArmClient).localNetConnClient +// +// name := d.Get("name").(string) +// location := d.Get("location").(string) +// resGroup := d.Get("resource_group_name").(string) +// ipAddress := d.Get("gateway_address").(string) +// +// // fetch the 'address_space_prefixes: +// prefixes := []string{} +// for _, pref := range d.Get("address_space").([]interface{}) { +// prefixes = append(prefixes, pref.(string)) +// } +// +// resp, err := lnetClient.CreateOrUpdate(resGroup, name, network.LocalNetworkGateway{ +// Name: &name, +// Location: &location, +// Properties: &network.LocalNetworkGatewayPropertiesFormat{ +// LocalNetworkAddressSpace: &network.AddressSpace{ +// AddressPrefixes: &prefixes, +// }, +// GatewayIPAddress: &ipAddress, +// }, +// }) +// if err != nil { +// return fmt.Errorf("Error creating Azure ARM Local Network Gateway '%s': %s", name, err) +// } +// +// d.SetId(*resp.ID) +// +// return resourceArmLocalNetworkGatewayRead(d, meta) +//} +// +//// resourceArmLocalNetworkGatewayRead goes ahead and reads the state of the corresponding ARM local network gateway. +//func resourceArmLocalNetworkGatewayRead(d *schema.ResourceData, meta interface{}) error { +// lnetClient := meta.(*ArmClient).localNetConnClient +// +// id, err := parseAzureResourceID(d.Id()) +// if err != nil { +// return err +// } +// name := id.Path["localNetworkGateways"] +// resGroup := id.ResourceGroup +// +// resp, err := lnetClient.Get(resGroup, name) +// if err != nil { +// if resp.StatusCode == http.StatusNotFound { +// d.SetId("") +// return nil +// } +// +// return fmt.Errorf("Error reading the state of Azure ARM local network gateway '%s': %s", name, err) +// } +// +// d.Set("gateway_address", resp.Properties.GatewayIPAddress) +// +// prefs := []string{} +// if ps := *resp.Properties.LocalNetworkAddressSpace.AddressPrefixes; ps != nil { +// prefs = ps +// } +// d.Set("address_space", prefs) +// +// return nil +//} +// +//// resourceArmLocalNetworkGatewayDelete deletes the specified ARM local network gateway. +//func resourceArmLocalNetworkGatewayDelete(d *schema.ResourceData, meta interface{}) error { +// lnetClient := meta.(*ArmClient).localNetConnClient +// +// id, err := parseAzureResourceID(d.Id()) +// if err != nil { +// return err +// } +// name := id.Path["localNetworkGateways"] +// resGroup := id.ResourceGroup +// +// _, err = lnetClient.Delete(resGroup, name) +// if err != nil { +// return fmt.Errorf("Error issuing Azure ARM delete request of local network gateway '%s': %s", name, err) +// } +// +// return nil +//} diff --git a/builtin/providers/azurerm/resource_arm_local_network_gateway_test.go b/builtin/providers/azurerm/resource_arm_local_network_gateway_test.go index 889a57e6ebf2..55b9e1e62499 100644 --- a/builtin/providers/azurerm/resource_arm_local_network_gateway_test.go +++ b/builtin/providers/azurerm/resource_arm_local_network_gateway_test.go @@ -1,108 +1,108 @@ package azurerm -import ( - "fmt" - "testing" - - "github.com/Azure/azure-sdk-for-go/core/http" - "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/terraform" -) - -func TestAccAzureRMLocalNetworkGateway_basic(t *testing.T) { - name := "azurerm_local_network_gateway.test" - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMLocalNetworkGatewayDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccAzureRMLocalNetworkGatewayConfig_basic, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMLocalNetworkGatewayExists(name), - resource.TestCheckResourceAttr(name, "gateway_address", "127.0.0.1"), - resource.TestCheckResourceAttr(name, "address_space.0", "127.0.0.0/8"), - ), - }, - }, - }) -} - -// testCheckAzureRMLocalNetworkGatewayExists returns the resurce.TestCheckFunc -// which checks whether or not the expected local network gateway exists both -// in the schema, and on Azure. -func testCheckAzureRMLocalNetworkGatewayExists(name string) resource.TestCheckFunc { - return func(s *terraform.State) error { - // first check within the schema for the local network gateway: - res, ok := s.RootModule().Resources[name] - if !ok { - return fmt.Errorf("Local network gateway '%s' not found.", name) - } - - // then, extract the name and the resource group: - id, err := parseAzureResourceID(res.Primary.ID) - if err != nil { - return err - } - localNetName := id.Path["localNetworkGateways"] - resGrp := id.ResourceGroup - - // and finally, check that it exists on Azure: - lnetClient := testAccProvider.Meta().(*ArmClient).localNetConnClient - - resp, err := lnetClient.Get(resGrp, localNetName) - if err != nil { - if resp.StatusCode == http.StatusNotFound { - return fmt.Errorf("Local network gateway '%s' (resource group '%s') does not exist on Azure.", localNetName, resGrp) - } - - return fmt.Errorf("Error reading the state of local network gateway '%s'.", localNetName) - } - - return nil - } -} - -func testCheckAzureRMLocalNetworkGatewayDestroy(s *terraform.State) error { - for _, res := range s.RootModule().Resources { - if res.Type != "azurerm_local_network_gateway" { - continue - } - - id, err := parseAzureResourceID(res.Primary.ID) - if err != nil { - return err - } - localNetName := id.Path["localNetworkGateways"] - resGrp := id.ResourceGroup - - lnetClient := testAccProvider.Meta().(*ArmClient).localNetConnClient - resp, err := lnetClient.Get(resGrp, localNetName) - - if err != nil { - return nil - } - - if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("Local network gateway still exists:\n%#v", resp.Properties) - } - } - - return nil -} - -var testAccAzureRMLocalNetworkGatewayConfig_basic = ` -resource "azurerm_resource_group" "test" { - name = "tftestingResourceGroup" - location = "West US" -} - -resource "azurerm_local_network_gateway" "test" { - name = "tftestingLocalNetworkGateway" - location = "${azurerm_resource_group.test.location}" - resource_group_name = "${azurerm_resource_group.test.name}" - gateway_address = "127.0.0.1" - address_space = ["127.0.0.0/8"] -} -` +//import ( +// "fmt" +// "testing" +// +// "github.com/Azure/azure-sdk-for-go/core/http" +// "github.com/hashicorp/terraform/helper/resource" +// "github.com/hashicorp/terraform/terraform" +//) +// +//func TestAccAzureRMLocalNetworkGateway_basic(t *testing.T) { +// name := "azurerm_local_network_gateway.test" +// +// resource.Test(t, resource.TestCase{ +// PreCheck: func() { testAccPreCheck(t) }, +// Providers: testAccProviders, +// CheckDestroy: testCheckAzureRMLocalNetworkGatewayDestroy, +// Steps: []resource.TestStep{ +// resource.TestStep{ +// Config: testAccAzureRMLocalNetworkGatewayConfig_basic, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMLocalNetworkGatewayExists(name), +// resource.TestCheckResourceAttr(name, "gateway_address", "127.0.0.1"), +// resource.TestCheckResourceAttr(name, "address_space.0", "127.0.0.0/8"), +// ), +// }, +// }, +// }) +//} +// +//// testCheckAzureRMLocalNetworkGatewayExists returns the resurce.TestCheckFunc +//// which checks whether or not the expected local network gateway exists both +//// in the schema, and on Azure. +//func testCheckAzureRMLocalNetworkGatewayExists(name string) resource.TestCheckFunc { +// return func(s *terraform.State) error { +// // first check within the schema for the local network gateway: +// res, ok := s.RootModule().Resources[name] +// if !ok { +// return fmt.Errorf("Local network gateway '%s' not found.", name) +// } +// +// // then, extract the name and the resource group: +// id, err := parseAzureResourceID(res.Primary.ID) +// if err != nil { +// return err +// } +// localNetName := id.Path["localNetworkGateways"] +// resGrp := id.ResourceGroup +// +// // and finally, check that it exists on Azure: +// lnetClient := testAccProvider.Meta().(*ArmClient).localNetConnClient +// +// resp, err := lnetClient.Get(resGrp, localNetName) +// if err != nil { +// if resp.StatusCode == http.StatusNotFound { +// return fmt.Errorf("Local network gateway '%s' (resource group '%s') does not exist on Azure.", localNetName, resGrp) +// } +// +// return fmt.Errorf("Error reading the state of local network gateway '%s'.", localNetName) +// } +// +// return nil +// } +//} +// +//func testCheckAzureRMLocalNetworkGatewayDestroy(s *terraform.State) error { +// for _, res := range s.RootModule().Resources { +// if res.Type != "azurerm_local_network_gateway" { +// continue +// } +// +// id, err := parseAzureResourceID(res.Primary.ID) +// if err != nil { +// return err +// } +// localNetName := id.Path["localNetworkGateways"] +// resGrp := id.ResourceGroup +// +// lnetClient := testAccProvider.Meta().(*ArmClient).localNetConnClient +// resp, err := lnetClient.Get(resGrp, localNetName) +// +// if err != nil { +// return nil +// } +// +// if resp.StatusCode != http.StatusNotFound { +// return fmt.Errorf("Local network gateway still exists:\n%#v", resp.Properties) +// } +// } +// +// return nil +//} +// +//var testAccAzureRMLocalNetworkGatewayConfig_basic = ` +//resource "azurerm_resource_group" "test" { +// name = "tftestingResourceGroup" +// location = "West US" +//} +// +//resource "azurerm_local_network_gateway" "test" { +// name = "tftestingLocalNetworkGateway" +// location = "${azurerm_resource_group.test.location}" +// resource_group_name = "${azurerm_resource_group.test.name}" +// gateway_address = "127.0.0.1" +// address_space = ["127.0.0.0/8"] +//} +//` diff --git a/builtin/providers/azurerm/resource_arm_network_interface_card.go b/builtin/providers/azurerm/resource_arm_network_interface_card.go index 174afc55b958..3207d3e87674 100644 --- a/builtin/providers/azurerm/resource_arm_network_interface_card.go +++ b/builtin/providers/azurerm/resource_arm_network_interface_card.go @@ -1,431 +1,431 @@ package azurerm -import ( - "bytes" - "fmt" - "log" - "net/http" - "strings" - "time" - - "github.com/Azure/azure-sdk-for-go/arm/network" - "github.com/hashicorp/terraform/helper/hashcode" - "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/helper/schema" -) - -func resourceArmNetworkInterface() *schema.Resource { - return &schema.Resource{ - Create: resourceArmNetworkInterfaceCreate, - Read: resourceArmNetworkInterfaceRead, - Update: resourceArmNetworkInterfaceCreate, - Delete: resourceArmNetworkInterfaceDelete, - - Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - - "location": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - StateFunc: azureRMNormalizeLocation, - }, - - "resource_group_name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - - "network_security_group_id": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Computed: true, - }, - - "mac_address": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Computed: true, - }, - - "private_ip_address": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - }, - - "virtual_machine_id": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Computed: true, - }, - - "ip_configuration": &schema.Schema{ - Type: schema.TypeSet, - Required: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - - "subnet_id": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - - "private_ip_address": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Computed: true, - }, - - "private_ip_address_allocation": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ValidateFunc: validateNetworkInterfacePrivateIpAddressAllocation, - }, - - "public_ip_address_id": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Computed: true, - }, - - "load_balancer_backend_address_pools_ids": &schema.Schema{ - Type: schema.TypeSet, - Optional: true, - Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - - "load_balancer_inbound_nat_rules_ids": &schema.Schema{ - Type: schema.TypeSet, - Optional: true, - Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - }, - }, - Set: resourceArmNetworkInterfaceIpConfigurationHash, - }, - - "dns_servers": &schema.Schema{ - Type: schema.TypeSet, - Optional: true, - Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - - "internal_dns_name_label": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Computed: true, - }, - - "applied_dns_servers": &schema.Schema{ - Type: schema.TypeSet, - Optional: true, - Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - - "internal_fqdn": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Computed: true, - }, - - "enable_ip_forwarding": &schema.Schema{ - Type: schema.TypeBool, - Optional: true, - Default: false, - }, - - "tags": tagsSchema(), - }, - } -} - -func resourceArmNetworkInterfaceCreate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient) - ifaceClient := client.ifaceClient - - log.Printf("[INFO] preparing arguments for Azure ARM Network Interface creation.") - - name := d.Get("name").(string) - location := d.Get("location").(string) - resGroup := d.Get("resource_group_name").(string) - enableIpForwarding := d.Get("enable_ip_forwarding").(bool) - tags := d.Get("tags").(map[string]interface{}) - - properties := network.InterfacePropertiesFormat{ - EnableIPForwarding: &enableIpForwarding, - } - - if v, ok := d.GetOk("network_security_group_id"); ok { - nsgId := v.(string) - properties.NetworkSecurityGroup = &network.SecurityGroup{ - ID: &nsgId, - } - } - - dns, hasDns := d.GetOk("dns_servers") - nameLabel, hasNameLabel := d.GetOk("internal_dns_name_label") - if hasDns || hasNameLabel { - ifaceDnsSettings := network.InterfaceDNSSettings{} - - if hasDns { - var dnsServers []string - dns := dns.(*schema.Set).List() - for _, v := range dns { - str := v.(string) - dnsServers = append(dnsServers, str) - } - ifaceDnsSettings.DNSServers = &dnsServers - } - - if hasNameLabel { - name_label := nameLabel.(string) - ifaceDnsSettings.InternalDNSNameLabel = &name_label - - } - - properties.DNSSettings = &ifaceDnsSettings - } - - ipConfigs, sgErr := expandAzureRmNetworkInterfaceIpConfigurations(d) - if sgErr != nil { - return fmt.Errorf("Error Building list of Network Interface IP Configurations: %s", sgErr) - } - if len(ipConfigs) > 0 { - properties.IPConfigurations = &ipConfigs - } - - iface := network.Interface{ - Name: &name, - Location: &location, - Properties: &properties, - Tags: expandTags(tags), - } - - resp, err := ifaceClient.CreateOrUpdate(resGroup, name, iface) - if err != nil { - return err - } - - d.SetId(*resp.ID) - - log.Printf("[DEBUG] Waiting for Network Interface (%s) to become available", name) - stateConf := &resource.StateChangeConf{ - Pending: []string{"Accepted", "Updating"}, - Target: []string{"Succeeded"}, - Refresh: networkInterfaceStateRefreshFunc(client, resGroup, name), - Timeout: 10 * time.Minute, - } - if _, err := stateConf.WaitForState(); err != nil { - return fmt.Errorf("Error waiting for Network Interface (%s) to become available: %s", name, err) - } - - return resourceArmNetworkInterfaceRead(d, meta) -} - -func resourceArmNetworkInterfaceRead(d *schema.ResourceData, meta interface{}) error { - ifaceClient := meta.(*ArmClient).ifaceClient - - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - resGroup := id.ResourceGroup - name := id.Path["networkInterfaces"] - - resp, err := ifaceClient.Get(resGroup, name, "") - if resp.StatusCode == http.StatusNotFound { - d.SetId("") - return nil - } - if err != nil { - return fmt.Errorf("Error making Read request on Azure Network Interface %s: %s", name, err) - } - - iface := *resp.Properties - - if iface.MacAddress != nil { - if *iface.MacAddress != "" { - d.Set("mac_address", iface.MacAddress) - } - } - - if iface.IPConfigurations != nil && len(*iface.IPConfigurations) > 0 { - var privateIPAddress *string - ///TODO: Change this to a loop when https://github.com/Azure/azure-sdk-for-go/issues/259 is fixed - if (*iface.IPConfigurations)[0].Properties != nil { - privateIPAddress = (*iface.IPConfigurations)[0].Properties.PrivateIPAddress - } - - if *privateIPAddress != "" { - d.Set("private_ip_address", *privateIPAddress) - } - } - - if iface.VirtualMachine != nil { - if *iface.VirtualMachine.ID != "" { - d.Set("virtual_machine_id", *iface.VirtualMachine.ID) - } - } - - if iface.DNSSettings != nil { - if iface.DNSSettings.AppliedDNSServers != nil && len(*iface.DNSSettings.AppliedDNSServers) > 0 { - dnsServers := make([]string, 0, len(*iface.DNSSettings.AppliedDNSServers)) - for _, dns := range *iface.DNSSettings.AppliedDNSServers { - dnsServers = append(dnsServers, dns) - } - - if err := d.Set("applied_dns_servers", dnsServers); err != nil { - return err - } - } - - if iface.DNSSettings.InternalFqdn != nil && *iface.DNSSettings.InternalFqdn != "" { - d.Set("internal_fqdn", iface.DNSSettings.InternalFqdn) - } - } - - flattenAndSetTags(d, resp.Tags) - - return nil -} - -func resourceArmNetworkInterfaceDelete(d *schema.ResourceData, meta interface{}) error { - ifaceClient := meta.(*ArmClient).ifaceClient - - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - resGroup := id.ResourceGroup - name := id.Path["networkInterfaces"] - - _, err = ifaceClient.Delete(resGroup, name) - - return err -} - -func networkInterfaceStateRefreshFunc(client *ArmClient, resourceGroupName string, ifaceName string) resource.StateRefreshFunc { - return func() (interface{}, string, error) { - res, err := client.ifaceClient.Get(resourceGroupName, ifaceName, "") - if err != nil { - return nil, "", fmt.Errorf("Error issuing read request in networkInterfaceStateRefreshFunc to Azure ARM for network interace '%s' (RG: '%s'): %s", ifaceName, resourceGroupName, err) - } - - return res, *res.Properties.ProvisioningState, nil - } -} - -func resourceArmNetworkInterfaceIpConfigurationHash(v interface{}) int { - var buf bytes.Buffer - m := v.(map[string]interface{}) - buf.WriteString(fmt.Sprintf("%s-", m["name"].(string))) - buf.WriteString(fmt.Sprintf("%s-", m["subnet_id"].(string))) - if m["private_ip_address"] != nil { - buf.WriteString(fmt.Sprintf("%s-", m["private_ip_address"].(string))) - } - buf.WriteString(fmt.Sprintf("%s-", m["private_ip_address_allocation"].(string))) - if m["public_ip_address_id"] != nil { - buf.WriteString(fmt.Sprintf("%s-", m["public_ip_address_id"].(string))) - } - - return hashcode.String(buf.String()) -} - -func validateNetworkInterfacePrivateIpAddressAllocation(v interface{}, k string) (ws []string, errors []error) { - value := strings.ToLower(v.(string)) - allocations := map[string]bool{ - "static": true, - "dynamic": true, - } - - if !allocations[value] { - errors = append(errors, fmt.Errorf("Network Interface Allocations can only be Static or Dynamic")) - } - return -} - -func expandAzureRmNetworkInterfaceIpConfigurations(d *schema.ResourceData) ([]network.InterfaceIPConfiguration, error) { - configs := d.Get("ip_configuration").(*schema.Set).List() - ipConfigs := make([]network.InterfaceIPConfiguration, 0, len(configs)) - - for _, configRaw := range configs { - data := configRaw.(map[string]interface{}) - - subnet_id := data["subnet_id"].(string) - private_ip_allocation_method := data["private_ip_address_allocation"].(string) - - properties := network.InterfaceIPConfigurationPropertiesFormat{ - Subnet: &network.Subnet{ - ID: &subnet_id, - }, - PrivateIPAllocationMethod: &private_ip_allocation_method, - } - - if v := data["private_ip_address"].(string); v != "" { - properties.PrivateIPAddress = &v - } - - if v := data["public_ip_address_id"].(string); v != "" { - properties.PublicIPAddress = &network.PublicIPAddress{ - ID: &v, - } - } - - if v, ok := data["load_balancer_backend_address_pools_ids"]; ok { - var ids []network.BackendAddressPool - pools := v.(*schema.Set).List() - for _, p := range pools { - pool_id := p.(string) - id := network.BackendAddressPool{ - ID: &pool_id, - } - - ids = append(ids, id) - } - - properties.LoadBalancerBackendAddressPools = &ids - } - - if v, ok := data["load_balancer_inbound_nat_rules_ids"]; ok { - var natRules []network.InboundNatRule - rules := v.(*schema.Set).List() - for _, r := range rules { - rule_id := r.(string) - rule := network.InboundNatRule{ - ID: &rule_id, - } - - natRules = append(natRules, rule) - } - - properties.LoadBalancerInboundNatRules = &natRules - } - - name := data["name"].(string) - ipConfig := network.InterfaceIPConfiguration{ - Name: &name, - Properties: &properties, - } - - ipConfigs = append(ipConfigs, ipConfig) - } - - return ipConfigs, nil -} +//import ( +// "bytes" +// "fmt" +// "log" +// "net/http" +// "strings" +// "time" +// +// "github.com/Azure/azure-sdk-for-go/arm/network" +// "github.com/hashicorp/terraform/helper/hashcode" +// "github.com/hashicorp/terraform/helper/resource" +// "github.com/hashicorp/terraform/helper/schema" +//) +// +//func resourceArmNetworkInterface() *schema.Resource { +// return &schema.Resource{ +// Create: resourceArmNetworkInterfaceCreate, +// Read: resourceArmNetworkInterfaceRead, +// Update: resourceArmNetworkInterfaceCreate, +// Delete: resourceArmNetworkInterfaceDelete, +// +// Schema: map[string]*schema.Schema{ +// "name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// }, +// +// "location": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// StateFunc: azureRMNormalizeLocation, +// }, +// +// "resource_group_name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// }, +// +// "network_security_group_id": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// Computed: true, +// }, +// +// "mac_address": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// Computed: true, +// }, +// +// "private_ip_address": &schema.Schema{ +// Type: schema.TypeString, +// Computed: true, +// }, +// +// "virtual_machine_id": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// Computed: true, +// }, +// +// "ip_configuration": &schema.Schema{ +// Type: schema.TypeSet, +// Required: true, +// Elem: &schema.Resource{ +// Schema: map[string]*schema.Schema{ +// "name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "subnet_id": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "private_ip_address": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// Computed: true, +// }, +// +// "private_ip_address_allocation": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ValidateFunc: validateNetworkInterfacePrivateIpAddressAllocation, +// }, +// +// "public_ip_address_id": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// Computed: true, +// }, +// +// "load_balancer_backend_address_pools_ids": &schema.Schema{ +// Type: schema.TypeSet, +// Optional: true, +// Computed: true, +// Elem: &schema.Schema{Type: schema.TypeString}, +// Set: schema.HashString, +// }, +// +// "load_balancer_inbound_nat_rules_ids": &schema.Schema{ +// Type: schema.TypeSet, +// Optional: true, +// Computed: true, +// Elem: &schema.Schema{Type: schema.TypeString}, +// Set: schema.HashString, +// }, +// }, +// }, +// Set: resourceArmNetworkInterfaceIpConfigurationHash, +// }, +// +// "dns_servers": &schema.Schema{ +// Type: schema.TypeSet, +// Optional: true, +// Computed: true, +// Elem: &schema.Schema{Type: schema.TypeString}, +// Set: schema.HashString, +// }, +// +// "internal_dns_name_label": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// Computed: true, +// }, +// +// "applied_dns_servers": &schema.Schema{ +// Type: schema.TypeSet, +// Optional: true, +// Computed: true, +// Elem: &schema.Schema{Type: schema.TypeString}, +// Set: schema.HashString, +// }, +// +// "internal_fqdn": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// Computed: true, +// }, +// +// "enable_ip_forwarding": &schema.Schema{ +// Type: schema.TypeBool, +// Optional: true, +// Default: false, +// }, +// +// "tags": tagsSchema(), +// }, +// } +//} +// +//func resourceArmNetworkInterfaceCreate(d *schema.ResourceData, meta interface{}) error { +// client := meta.(*ArmClient) +// ifaceClient := client.ifaceClient +// +// log.Printf("[INFO] preparing arguments for Azure ARM Network Interface creation.") +// +// name := d.Get("name").(string) +// location := d.Get("location").(string) +// resGroup := d.Get("resource_group_name").(string) +// enableIpForwarding := d.Get("enable_ip_forwarding").(bool) +// tags := d.Get("tags").(map[string]interface{}) +// +// properties := network.InterfacePropertiesFormat{ +// EnableIPForwarding: &enableIpForwarding, +// } +// +// if v, ok := d.GetOk("network_security_group_id"); ok { +// nsgId := v.(string) +// properties.NetworkSecurityGroup = &network.SecurityGroup{ +// ID: &nsgId, +// } +// } +// +// dns, hasDns := d.GetOk("dns_servers") +// nameLabel, hasNameLabel := d.GetOk("internal_dns_name_label") +// if hasDns || hasNameLabel { +// ifaceDnsSettings := network.InterfaceDNSSettings{} +// +// if hasDns { +// var dnsServers []string +// dns := dns.(*schema.Set).List() +// for _, v := range dns { +// str := v.(string) +// dnsServers = append(dnsServers, str) +// } +// ifaceDnsSettings.DNSServers = &dnsServers +// } +// +// if hasNameLabel { +// name_label := nameLabel.(string) +// ifaceDnsSettings.InternalDNSNameLabel = &name_label +// +// } +// +// properties.DNSSettings = &ifaceDnsSettings +// } +// +// ipConfigs, sgErr := expandAzureRmNetworkInterfaceIpConfigurations(d) +// if sgErr != nil { +// return fmt.Errorf("Error Building list of Network Interface IP Configurations: %s", sgErr) +// } +// if len(ipConfigs) > 0 { +// properties.IPConfigurations = &ipConfigs +// } +// +// iface := network.Interface{ +// Name: &name, +// Location: &location, +// Properties: &properties, +// Tags: expandTags(tags), +// } +// +// resp, err := ifaceClient.CreateOrUpdate(resGroup, name, iface) +// if err != nil { +// return err +// } +// +// d.SetId(*resp.ID) +// +// log.Printf("[DEBUG] Waiting for Network Interface (%s) to become available", name) +// stateConf := &resource.StateChangeConf{ +// Pending: []string{"Accepted", "Updating"}, +// Target: []string{"Succeeded"}, +// Refresh: networkInterfaceStateRefreshFunc(client, resGroup, name), +// Timeout: 10 * time.Minute, +// } +// if _, err := stateConf.WaitForState(); err != nil { +// return fmt.Errorf("Error waiting for Network Interface (%s) to become available: %s", name, err) +// } +// +// return resourceArmNetworkInterfaceRead(d, meta) +//} +// +//func resourceArmNetworkInterfaceRead(d *schema.ResourceData, meta interface{}) error { +// ifaceClient := meta.(*ArmClient).ifaceClient +// +// id, err := parseAzureResourceID(d.Id()) +// if err != nil { +// return err +// } +// resGroup := id.ResourceGroup +// name := id.Path["networkInterfaces"] +// +// resp, err := ifaceClient.Get(resGroup, name, "") +// if resp.StatusCode == http.StatusNotFound { +// d.SetId("") +// return nil +// } +// if err != nil { +// return fmt.Errorf("Error making Read request on Azure Network Interface %s: %s", name, err) +// } +// +// iface := *resp.Properties +// +// if iface.MacAddress != nil { +// if *iface.MacAddress != "" { +// d.Set("mac_address", iface.MacAddress) +// } +// } +// +// if iface.IPConfigurations != nil && len(*iface.IPConfigurations) > 0 { +// var privateIPAddress *string +// ///TODO: Change this to a loop when https://github.com/Azure/azure-sdk-for-go/issues/259 is fixed +// if (*iface.IPConfigurations)[0].Properties != nil { +// privateIPAddress = (*iface.IPConfigurations)[0].Properties.PrivateIPAddress +// } +// +// if *privateIPAddress != "" { +// d.Set("private_ip_address", *privateIPAddress) +// } +// } +// +// if iface.VirtualMachine != nil { +// if *iface.VirtualMachine.ID != "" { +// d.Set("virtual_machine_id", *iface.VirtualMachine.ID) +// } +// } +// +// if iface.DNSSettings != nil { +// if iface.DNSSettings.AppliedDNSServers != nil && len(*iface.DNSSettings.AppliedDNSServers) > 0 { +// dnsServers := make([]string, 0, len(*iface.DNSSettings.AppliedDNSServers)) +// for _, dns := range *iface.DNSSettings.AppliedDNSServers { +// dnsServers = append(dnsServers, dns) +// } +// +// if err := d.Set("applied_dns_servers", dnsServers); err != nil { +// return err +// } +// } +// +// if iface.DNSSettings.InternalFqdn != nil && *iface.DNSSettings.InternalFqdn != "" { +// d.Set("internal_fqdn", iface.DNSSettings.InternalFqdn) +// } +// } +// +// flattenAndSetTags(d, resp.Tags) +// +// return nil +//} +// +//func resourceArmNetworkInterfaceDelete(d *schema.ResourceData, meta interface{}) error { +// ifaceClient := meta.(*ArmClient).ifaceClient +// +// id, err := parseAzureResourceID(d.Id()) +// if err != nil { +// return err +// } +// resGroup := id.ResourceGroup +// name := id.Path["networkInterfaces"] +// +// _, err = ifaceClient.Delete(resGroup, name) +// +// return err +//} +// +//func networkInterfaceStateRefreshFunc(client *ArmClient, resourceGroupName string, ifaceName string) resource.StateRefreshFunc { +// return func() (interface{}, string, error) { +// res, err := client.ifaceClient.Get(resourceGroupName, ifaceName, "") +// if err != nil { +// return nil, "", fmt.Errorf("Error issuing read request in networkInterfaceStateRefreshFunc to Azure ARM for network interace '%s' (RG: '%s'): %s", ifaceName, resourceGroupName, err) +// } +// +// return res, *res.Properties.ProvisioningState, nil +// } +//} +// +//func resourceArmNetworkInterfaceIpConfigurationHash(v interface{}) int { +// var buf bytes.Buffer +// m := v.(map[string]interface{}) +// buf.WriteString(fmt.Sprintf("%s-", m["name"].(string))) +// buf.WriteString(fmt.Sprintf("%s-", m["subnet_id"].(string))) +// if m["private_ip_address"] != nil { +// buf.WriteString(fmt.Sprintf("%s-", m["private_ip_address"].(string))) +// } +// buf.WriteString(fmt.Sprintf("%s-", m["private_ip_address_allocation"].(string))) +// if m["public_ip_address_id"] != nil { +// buf.WriteString(fmt.Sprintf("%s-", m["public_ip_address_id"].(string))) +// } +// +// return hashcode.String(buf.String()) +//} +// +//func validateNetworkInterfacePrivateIpAddressAllocation(v interface{}, k string) (ws []string, errors []error) { +// value := strings.ToLower(v.(string)) +// allocations := map[string]bool{ +// "static": true, +// "dynamic": true, +// } +// +// if !allocations[value] { +// errors = append(errors, fmt.Errorf("Network Interface Allocations can only be Static or Dynamic")) +// } +// return +//} +// +//func expandAzureRmNetworkInterfaceIpConfigurations(d *schema.ResourceData) ([]network.InterfaceIPConfiguration, error) { +// configs := d.Get("ip_configuration").(*schema.Set).List() +// ipConfigs := make([]network.InterfaceIPConfiguration, 0, len(configs)) +// +// for _, configRaw := range configs { +// data := configRaw.(map[string]interface{}) +// +// subnet_id := data["subnet_id"].(string) +// private_ip_allocation_method := data["private_ip_address_allocation"].(string) +// +// properties := network.InterfaceIPConfigurationPropertiesFormat{ +// Subnet: &network.Subnet{ +// ID: &subnet_id, +// }, +// PrivateIPAllocationMethod: &private_ip_allocation_method, +// } +// +// if v := data["private_ip_address"].(string); v != "" { +// properties.PrivateIPAddress = &v +// } +// +// if v := data["public_ip_address_id"].(string); v != "" { +// properties.PublicIPAddress = &network.PublicIPAddress{ +// ID: &v, +// } +// } +// +// if v, ok := data["load_balancer_backend_address_pools_ids"]; ok { +// var ids []network.BackendAddressPool +// pools := v.(*schema.Set).List() +// for _, p := range pools { +// pool_id := p.(string) +// id := network.BackendAddressPool{ +// ID: &pool_id, +// } +// +// ids = append(ids, id) +// } +// +// properties.LoadBalancerBackendAddressPools = &ids +// } +// +// if v, ok := data["load_balancer_inbound_nat_rules_ids"]; ok { +// var natRules []network.InboundNatRule +// rules := v.(*schema.Set).List() +// for _, r := range rules { +// rule_id := r.(string) +// rule := network.InboundNatRule{ +// ID: &rule_id, +// } +// +// natRules = append(natRules, rule) +// } +// +// properties.LoadBalancerInboundNatRules = &natRules +// } +// +// name := data["name"].(string) +// ipConfig := network.InterfaceIPConfiguration{ +// Name: &name, +// Properties: &properties, +// } +// +// ipConfigs = append(ipConfigs, ipConfig) +// } +// +// return ipConfigs, nil +//} diff --git a/builtin/providers/azurerm/resource_arm_network_interface_card_test.go b/builtin/providers/azurerm/resource_arm_network_interface_card_test.go index 156b4bdf5580..83149871ecbb 100644 --- a/builtin/providers/azurerm/resource_arm_network_interface_card_test.go +++ b/builtin/providers/azurerm/resource_arm_network_interface_card_test.go @@ -1,86 +1,16 @@ package azurerm -import ( - "fmt" - "net/http" - "testing" - - "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/terraform" -) - -func TestAccAzureRMNetworkInterface_basic(t *testing.T) { - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMNetworkInterfaceDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccAzureRMNetworkInterface_basic, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"), - ), - }, - }, - }) -} - -func TestAccAzureRMNetworkInterfaceenableIPForwarding(t *testing.T) { - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMNetworkInterfaceDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccAzureRMNetworkInterface_ipForwarding, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"), - resource.TestCheckResourceAttr( - "azurerm_network_interface.test", "enable_ip_forwarding", "true"), - ), - }, - }, - }) -} - -func TestAccAzureRMNetworkInterface_withTags(t *testing.T) { - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMNetworkInterfaceDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccAzureRMNetworkInterface_withTags, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"), - resource.TestCheckResourceAttr( - "azurerm_network_interface.test", "tags.#", "2"), - resource.TestCheckResourceAttr( - "azurerm_network_interface.test", "tags.environment", "Production"), - resource.TestCheckResourceAttr( - "azurerm_network_interface.test", "tags.cost_center", "MSFT"), - ), - }, - - resource.TestStep{ - Config: testAccAzureRMNetworkInterface_withTagsUpdate, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"), - resource.TestCheckResourceAttr( - "azurerm_network_interface.test", "tags.#", "1"), - resource.TestCheckResourceAttr( - "azurerm_network_interface.test", "tags.environment", "staging"), - ), - }, - }, - }) -} - -///TODO: Re-enable this test when https://github.com/Azure/azure-sdk-for-go/issues/259 is fixed -//func TestAccAzureRMNetworkInterface_addingIpConfigurations(t *testing.T) { +// +//import ( +// "fmt" +// "net/http" +// "testing" +// +// "github.com/hashicorp/terraform/helper/resource" +// "github.com/hashicorp/terraform/terraform" +//) +// +//func TestAccAzureRMNetworkInterface_basic(t *testing.T) { // // resource.Test(t, resource.TestCase{ // PreCheck: func() { testAccPreCheck(t) }, @@ -91,221 +21,182 @@ func TestAccAzureRMNetworkInterface_withTags(t *testing.T) { // Config: testAccAzureRMNetworkInterface_basic, // Check: resource.ComposeTestCheckFunc( // testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"), +// ), +// }, +// }, +// }) +//} +// +//func TestAccAzureRMNetworkInterfaceenableIPForwarding(t *testing.T) { +// +// resource.Test(t, resource.TestCase{ +// PreCheck: func() { testAccPreCheck(t) }, +// Providers: testAccProviders, +// CheckDestroy: testCheckAzureRMNetworkInterfaceDestroy, +// Steps: []resource.TestStep{ +// resource.TestStep{ +// Config: testAccAzureRMNetworkInterface_ipForwarding, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"), +// resource.TestCheckResourceAttr( +// "azurerm_network_interface.test", "enable_ip_forwarding", "true"), +// ), +// }, +// }, +// }) +//} +// +//func TestAccAzureRMNetworkInterface_withTags(t *testing.T) { +// +// resource.Test(t, resource.TestCase{ +// PreCheck: func() { testAccPreCheck(t) }, +// Providers: testAccProviders, +// CheckDestroy: testCheckAzureRMNetworkInterfaceDestroy, +// Steps: []resource.TestStep{ +// resource.TestStep{ +// Config: testAccAzureRMNetworkInterface_withTags, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"), +// resource.TestCheckResourceAttr( +// "azurerm_network_interface.test", "tags.#", "2"), +// resource.TestCheckResourceAttr( +// "azurerm_network_interface.test", "tags.environment", "Production"), // resource.TestCheckResourceAttr( -// "azurerm_network_interface.test", "ip_configuration.#", "1"), +// "azurerm_network_interface.test", "tags.cost_center", "MSFT"), // ), // }, // // resource.TestStep{ -// Config: testAccAzureRMNetworkInterface_extraIpConfiguration, +// Config: testAccAzureRMNetworkInterface_withTagsUpdate, // Check: resource.ComposeTestCheckFunc( // testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"), // resource.TestCheckResourceAttr( -// "azurerm_network_interface.test", "ip_configuration.#", "2"), +// "azurerm_network_interface.test", "tags.#", "1"), +// resource.TestCheckResourceAttr( +// "azurerm_network_interface.test", "tags.environment", "staging"), // ), // }, // }, // }) //} - -func testCheckAzureRMNetworkInterfaceExists(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) - } - - name := rs.Primary.Attributes["name"] - resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] - if !hasResourceGroup { - return fmt.Errorf("Bad: no resource group found in state for availability set: %s", name) - } - - conn := testAccProvider.Meta().(*ArmClient).ifaceClient - - resp, err := conn.Get(resourceGroup, name, "") - if err != nil { - return fmt.Errorf("Bad: Get on ifaceClient: %s", err) - } - - if resp.StatusCode == http.StatusNotFound { - return fmt.Errorf("Bad: Network Interface %q (resource group: %q) does not exist", name, resourceGroup) - } - - return nil - } -} - -func testCheckAzureRMNetworkInterfaceDestroy(s *terraform.State) error { - conn := testAccProvider.Meta().(*ArmClient).ifaceClient - - for _, rs := range s.RootModule().Resources { - if rs.Type != "azurerm_network_interface" { - continue - } - - name := rs.Primary.Attributes["name"] - resourceGroup := rs.Primary.Attributes["resource_group_name"] - - resp, err := conn.Get(resourceGroup, name, "") - - if err != nil { - return nil - } - - if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("Network Interface still exists:\n%#v", resp.Properties) - } - } - - return nil -} - -var testAccAzureRMNetworkInterface_basic = ` -resource "azurerm_resource_group" "test" { - name = "acceptanceTestResourceGroup1" - location = "West US" -} - -resource "azurerm_virtual_network" "test" { - name = "acceptanceTestVirtualNetwork1" - address_space = ["10.0.0.0/16"] - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" -} - -resource "azurerm_subnet" "test" { - name = "testsubnet" - resource_group_name = "${azurerm_resource_group.test.name}" - virtual_network_name = "${azurerm_virtual_network.test.name}" - address_prefix = "10.0.2.0/24" -} - -resource "azurerm_network_interface" "test" { - name = "acceptanceTestNetworkInterface1" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - - ip_configuration { - name = "testconfiguration1" - subnet_id = "${azurerm_subnet.test.id}" - private_ip_address_allocation = "dynamic" - } -} -` - -var testAccAzureRMNetworkInterface_ipForwarding = ` -resource "azurerm_resource_group" "test" { - name = "acceptanceTestResourceGroup1" - location = "West US" -} - -resource "azurerm_virtual_network" "test" { - name = "acceptanceTestVirtualNetwork1" - address_space = ["10.0.0.0/16"] - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" -} - -resource "azurerm_subnet" "test" { - name = "testsubnet" - resource_group_name = "${azurerm_resource_group.test.name}" - virtual_network_name = "${azurerm_virtual_network.test.name}" - address_prefix = "10.0.2.0/24" -} - -resource "azurerm_network_interface" "test" { - name = "acceptanceTestNetworkInterface1" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - enable_ip_forwarding = true - - ip_configuration { - name = "testconfiguration1" - subnet_id = "${azurerm_subnet.test.id}" - private_ip_address_allocation = "dynamic" - } -} -` - -var testAccAzureRMNetworkInterface_withTags = ` -resource "azurerm_resource_group" "test" { - name = "acceptanceTestResourceGroup1" - location = "West US" -} - -resource "azurerm_virtual_network" "test" { - name = "acceptanceTestVirtualNetwork1" - address_space = ["10.0.0.0/16"] - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" -} - -resource "azurerm_subnet" "test" { - name = "testsubnet" - resource_group_name = "${azurerm_resource_group.test.name}" - virtual_network_name = "${azurerm_virtual_network.test.name}" - address_prefix = "10.0.2.0/24" -} - -resource "azurerm_network_interface" "test" { - name = "acceptanceTestNetworkInterface1" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - - ip_configuration { - name = "testconfiguration1" - subnet_id = "${azurerm_subnet.test.id}" - private_ip_address_allocation = "dynamic" - } - - tags { - environment = "Production" - cost_center = "MSFT" - } -} -` - -var testAccAzureRMNetworkInterface_withTagsUpdate = ` -resource "azurerm_resource_group" "test" { - name = "acceptanceTestResourceGroup1" - location = "West US" -} - -resource "azurerm_virtual_network" "test" { - name = "acceptanceTestVirtualNetwork1" - address_space = ["10.0.0.0/16"] - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" -} - -resource "azurerm_subnet" "test" { - name = "testsubnet" - resource_group_name = "${azurerm_resource_group.test.name}" - virtual_network_name = "${azurerm_virtual_network.test.name}" - address_prefix = "10.0.2.0/24" -} - -resource "azurerm_network_interface" "test" { - name = "acceptanceTestNetworkInterface1" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - - ip_configuration { - name = "testconfiguration1" - subnet_id = "${azurerm_subnet.test.id}" - private_ip_address_allocation = "dynamic" - } - - tags { - environment = "staging" - } -} -` - -//TODO: Re-enable this test when https://github.com/Azure/azure-sdk-for-go/issues/259 is fixed -//var testAccAzureRMNetworkInterface_extraIpConfiguration = ` +// +/////TODO: Re-enable this test when https://github.com/Azure/azure-sdk-for-go/issues/259 is fixed +////func TestAccAzureRMNetworkInterface_addingIpConfigurations(t *testing.T) { +//// +//// resource.Test(t, resource.TestCase{ +//// PreCheck: func() { testAccPreCheck(t) }, +//// Providers: testAccProviders, +//// CheckDestroy: testCheckAzureRMNetworkInterfaceDestroy, +//// Steps: []resource.TestStep{ +//// resource.TestStep{ +//// Config: testAccAzureRMNetworkInterface_basic, +//// Check: resource.ComposeTestCheckFunc( +//// testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"), +//// resource.TestCheckResourceAttr( +//// "azurerm_network_interface.test", "ip_configuration.#", "1"), +//// ), +//// }, +//// +//// resource.TestStep{ +//// Config: testAccAzureRMNetworkInterface_extraIpConfiguration, +//// Check: resource.ComposeTestCheckFunc( +//// testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"), +//// resource.TestCheckResourceAttr( +//// "azurerm_network_interface.test", "ip_configuration.#", "2"), +//// ), +//// }, +//// }, +//// }) +////} +// +//func testCheckAzureRMNetworkInterfaceExists(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) +// } +// +// name := rs.Primary.Attributes["name"] +// resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] +// if !hasResourceGroup { +// return fmt.Errorf("Bad: no resource group found in state for availability set: %s", name) +// } +// +// conn := testAccProvider.Meta().(*ArmClient).ifaceClient +// +// resp, err := conn.Get(resourceGroup, name, "") +// if err != nil { +// return fmt.Errorf("Bad: Get on ifaceClient: %s", err) +// } +// +// if resp.StatusCode == http.StatusNotFound { +// return fmt.Errorf("Bad: Network Interface %q (resource group: %q) does not exist", name, resourceGroup) +// } +// +// return nil +// } +//} +// +//func testCheckAzureRMNetworkInterfaceDestroy(s *terraform.State) error { +// conn := testAccProvider.Meta().(*ArmClient).ifaceClient +// +// for _, rs := range s.RootModule().Resources { +// if rs.Type != "azurerm_network_interface" { +// continue +// } +// +// name := rs.Primary.Attributes["name"] +// resourceGroup := rs.Primary.Attributes["resource_group_name"] +// +// resp, err := conn.Get(resourceGroup, name, "") +// +// if err != nil { +// return nil +// } +// +// if resp.StatusCode != http.StatusNotFound { +// return fmt.Errorf("Network Interface still exists:\n%#v", resp.Properties) +// } +// } +// +// return nil +//} +// +//var testAccAzureRMNetworkInterface_basic = ` +//resource "azurerm_resource_group" "test" { +// name = "acceptanceTestResourceGroup1" +// location = "West US" +//} +// +//resource "azurerm_virtual_network" "test" { +// name = "acceptanceTestVirtualNetwork1" +// address_space = ["10.0.0.0/16"] +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +//} +// +//resource "azurerm_subnet" "test" { +// name = "testsubnet" +// resource_group_name = "${azurerm_resource_group.test.name}" +// virtual_network_name = "${azurerm_virtual_network.test.name}" +// address_prefix = "10.0.2.0/24" +//} +// +//resource "azurerm_network_interface" "test" { +// name = "acceptanceTestNetworkInterface1" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// +// ip_configuration { +// name = "testconfiguration1" +// subnet_id = "${azurerm_subnet.test.id}" +// private_ip_address_allocation = "dynamic" +// } +//} +//` +// +//var testAccAzureRMNetworkInterface_ipForwarding = ` //resource "azurerm_resource_group" "test" { // name = "acceptanceTestResourceGroup1" // location = "West US" @@ -325,11 +216,38 @@ resource "azurerm_network_interface" "test" { // address_prefix = "10.0.2.0/24" //} // -//resource "azurerm_subnet" "test1" { -// name = "testsubnet1" +//resource "azurerm_network_interface" "test" { +// name = "acceptanceTestNetworkInterface1" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// enable_ip_forwarding = true +// +// ip_configuration { +// name = "testconfiguration1" +// subnet_id = "${azurerm_subnet.test.id}" +// private_ip_address_allocation = "dynamic" +// } +//} +//` +// +//var testAccAzureRMNetworkInterface_withTags = ` +//resource "azurerm_resource_group" "test" { +// name = "acceptanceTestResourceGroup1" +// location = "West US" +//} +// +//resource "azurerm_virtual_network" "test" { +// name = "acceptanceTestVirtualNetwork1" +// address_space = ["10.0.0.0/16"] +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +//} +// +//resource "azurerm_subnet" "test" { +// name = "testsubnet" // resource_group_name = "${azurerm_resource_group.test.name}" // virtual_network_name = "${azurerm_virtual_network.test.name}" -// address_prefix = "10.0.1.0/24" +// address_prefix = "10.0.2.0/24" //} // //resource "azurerm_network_interface" "test" { @@ -343,11 +261,94 @@ resource "azurerm_network_interface" "test" { // private_ip_address_allocation = "dynamic" // } // +// tags { +// environment = "Production" +// cost_center = "MSFT" +// } +//} +//` +// +//var testAccAzureRMNetworkInterface_withTagsUpdate = ` +//resource "azurerm_resource_group" "test" { +// name = "acceptanceTestResourceGroup1" +// location = "West US" +//} +// +//resource "azurerm_virtual_network" "test" { +// name = "acceptanceTestVirtualNetwork1" +// address_space = ["10.0.0.0/16"] +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +//} +// +//resource "azurerm_subnet" "test" { +// name = "testsubnet" +// resource_group_name = "${azurerm_resource_group.test.name}" +// virtual_network_name = "${azurerm_virtual_network.test.name}" +// address_prefix = "10.0.2.0/24" +//} +// +//resource "azurerm_network_interface" "test" { +// name = "acceptanceTestNetworkInterface1" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// // ip_configuration { -// name = "testconfiguration2" -// subnet_id = "${azurerm_subnet.test1.id}" +// name = "testconfiguration1" +// subnet_id = "${azurerm_subnet.test.id}" // private_ip_address_allocation = "dynamic" -// primary = true +// } +// +// tags { +// environment = "staging" // } //} //` +// +////TODO: Re-enable this test when https://github.com/Azure/azure-sdk-for-go/issues/259 is fixed +////var testAccAzureRMNetworkInterface_extraIpConfiguration = ` +////resource "azurerm_resource_group" "test" { +//// name = "acceptanceTestResourceGroup1" +//// location = "West US" +////} +//// +////resource "azurerm_virtual_network" "test" { +//// name = "acceptanceTestVirtualNetwork1" +//// address_space = ["10.0.0.0/16"] +//// location = "West US" +//// resource_group_name = "${azurerm_resource_group.test.name}" +////} +//// +////resource "azurerm_subnet" "test" { +//// name = "testsubnet" +//// resource_group_name = "${azurerm_resource_group.test.name}" +//// virtual_network_name = "${azurerm_virtual_network.test.name}" +//// address_prefix = "10.0.2.0/24" +////} +//// +////resource "azurerm_subnet" "test1" { +//// name = "testsubnet1" +//// resource_group_name = "${azurerm_resource_group.test.name}" +//// virtual_network_name = "${azurerm_virtual_network.test.name}" +//// address_prefix = "10.0.1.0/24" +////} +//// +////resource "azurerm_network_interface" "test" { +//// name = "acceptanceTestNetworkInterface1" +//// location = "West US" +//// resource_group_name = "${azurerm_resource_group.test.name}" +//// +//// ip_configuration { +//// name = "testconfiguration1" +//// subnet_id = "${azurerm_subnet.test.id}" +//// private_ip_address_allocation = "dynamic" +//// } +//// +//// ip_configuration { +//// name = "testconfiguration2" +//// subnet_id = "${azurerm_subnet.test1.id}" +//// private_ip_address_allocation = "dynamic" +//// primary = true +//// } +////} +////` diff --git a/builtin/providers/azurerm/resource_arm_network_security_group.go b/builtin/providers/azurerm/resource_arm_network_security_group.go index cc73f509c739..4d9569c41273 100644 --- a/builtin/providers/azurerm/resource_arm_network_security_group.go +++ b/builtin/providers/azurerm/resource_arm_network_security_group.go @@ -1,301 +1,301 @@ package azurerm -import ( - "bytes" - "fmt" - "log" - "net/http" - "time" - - "github.com/Azure/azure-sdk-for-go/arm/network" - "github.com/hashicorp/terraform/helper/hashcode" - "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/helper/schema" -) - -func resourceArmNetworkSecurityGroup() *schema.Resource { - return &schema.Resource{ - Create: resourceArmNetworkSecurityGroupCreate, - Read: resourceArmNetworkSecurityGroupRead, - Update: resourceArmNetworkSecurityGroupCreate, - Delete: resourceArmNetworkSecurityGroupDelete, - - Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - - "location": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - StateFunc: azureRMNormalizeLocation, - }, - - "resource_group_name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - - "security_rule": &schema.Schema{ - Type: schema.TypeSet, - Optional: true, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - - "description": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { - value := v.(string) - if len(value) > 140 { - errors = append(errors, fmt.Errorf( - "The network security rule description can be no longer than 140 chars")) - } - return - }, - }, - - "protocol": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ValidateFunc: validateNetworkSecurityRuleProtocol, - }, - - "source_port_range": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - - "destination_port_range": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - - "source_address_prefix": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - - "destination_address_prefix": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - - "access": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ValidateFunc: validateNetworkSecurityRuleAccess, - }, - - "priority": &schema.Schema{ - Type: schema.TypeInt, - Required: true, - ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { - value := v.(int) - if value < 100 || value > 4096 { - errors = append(errors, fmt.Errorf( - "The `priority` can only be between 100 and 4096")) - } - return - }, - }, - - "direction": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ValidateFunc: validateNetworkSecurityRuleDirection, - }, - }, - }, - Set: resourceArmNetworkSecurityGroupRuleHash, - }, - - "tags": tagsSchema(), - }, - } -} - -func resourceArmNetworkSecurityGroupCreate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient) - secClient := client.secGroupClient - - name := d.Get("name").(string) - location := d.Get("location").(string) - resGroup := d.Get("resource_group_name").(string) - tags := d.Get("tags").(map[string]interface{}) - - sgRules, sgErr := expandAzureRmSecurityRules(d) - if sgErr != nil { - return fmt.Errorf("Error Building list of Network Security Group Rules: %s", sgErr) - } - - sg := network.SecurityGroup{ - Name: &name, - Location: &location, - Properties: &network.SecurityGroupPropertiesFormat{ - SecurityRules: &sgRules, - }, - Tags: expandTags(tags), - } - - resp, err := secClient.CreateOrUpdate(resGroup, name, sg) - if err != nil { - return err - } - - d.SetId(*resp.ID) - - log.Printf("[DEBUG] Waiting for Network Security Group (%s) to become available", name) - stateConf := &resource.StateChangeConf{ - Pending: []string{"Accepted", "Updating"}, - Target: []string{"Succeeded"}, - Refresh: securityGroupStateRefreshFunc(client, resGroup, name), - Timeout: 10 * time.Minute, - } - if _, err := stateConf.WaitForState(); err != nil { - return fmt.Errorf("Error waiting for Network Securty Group (%s) to become available: %s", name, err) - } - - return resourceArmNetworkSecurityGroupRead(d, meta) -} - -func resourceArmNetworkSecurityGroupRead(d *schema.ResourceData, meta interface{}) error { - secGroupClient := meta.(*ArmClient).secGroupClient - - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - resGroup := id.ResourceGroup - name := id.Path["networkSecurityGroups"] - - resp, err := secGroupClient.Get(resGroup, name, "") - if resp.StatusCode == http.StatusNotFound { - d.SetId("") - return nil - } - if err != nil { - return fmt.Errorf("Error making Read request on Azure Network Security Group %s: %s", name, err) - } - - if resp.Properties.SecurityRules != nil { - d.Set("security_rule", flattenNetworkSecurityRules(resp.Properties.SecurityRules)) - } - - flattenAndSetTags(d, resp.Tags) - - return nil -} - -func resourceArmNetworkSecurityGroupDelete(d *schema.ResourceData, meta interface{}) error { - secGroupClient := meta.(*ArmClient).secGroupClient - - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - resGroup := id.ResourceGroup - name := id.Path["networkSecurityGroups"] - - _, err = secGroupClient.Delete(resGroup, name) - - return err -} - -func resourceArmNetworkSecurityGroupRuleHash(v interface{}) int { - var buf bytes.Buffer - m := v.(map[string]interface{}) - buf.WriteString(fmt.Sprintf("%s-", m["protocol"].(string))) - buf.WriteString(fmt.Sprintf("%s-", m["source_port_range"].(string))) - buf.WriteString(fmt.Sprintf("%s-", m["destination_port_range"].(string))) - buf.WriteString(fmt.Sprintf("%s-", m["source_address_prefix"].(string))) - buf.WriteString(fmt.Sprintf("%s-", m["destination_address_prefix"].(string))) - buf.WriteString(fmt.Sprintf("%s-", m["access"].(string))) - buf.WriteString(fmt.Sprintf("%d-", m["priority"].(int))) - buf.WriteString(fmt.Sprintf("%s-", m["direction"].(string))) - - return hashcode.String(buf.String()) -} - -func securityGroupStateRefreshFunc(client *ArmClient, resourceGroupName string, securityGroupName string) resource.StateRefreshFunc { - return func() (interface{}, string, error) { - res, err := client.secGroupClient.Get(resourceGroupName, securityGroupName, "") - if err != nil { - return nil, "", fmt.Errorf("Error issuing read request in securityGroupStateRefreshFunc to Azure ARM for network security group '%s' (RG: '%s'): %s", securityGroupName, resourceGroupName, err) - } - - return res, *res.Properties.ProvisioningState, nil - } -} - -func flattenNetworkSecurityRules(rules *[]network.SecurityRule) []map[string]interface{} { - result := make([]map[string]interface{}, 0, len(*rules)) - for _, rule := range *rules { - sgRule := make(map[string]interface{}) - sgRule["name"] = *rule.Name - sgRule["destination_address_prefix"] = *rule.Properties.DestinationAddressPrefix - sgRule["destination_port_range"] = *rule.Properties.DestinationPortRange - sgRule["source_address_prefix"] = *rule.Properties.SourceAddressPrefix - sgRule["source_port_range"] = *rule.Properties.SourcePortRange - sgRule["priority"] = int(*rule.Properties.Priority) - sgRule["access"] = rule.Properties.Access - sgRule["direction"] = rule.Properties.Direction - sgRule["protocol"] = rule.Properties.Protocol - - if rule.Properties.Description != nil { - sgRule["description"] = *rule.Properties.Description - } - - result = append(result, sgRule) - } - return result -} - -func expandAzureRmSecurityRules(d *schema.ResourceData) ([]network.SecurityRule, error) { - sgRules := d.Get("security_rule").(*schema.Set).List() - rules := make([]network.SecurityRule, 0, len(sgRules)) - - for _, sgRaw := range sgRules { - data := sgRaw.(map[string]interface{}) - - source_port_range := data["source_port_range"].(string) - destination_port_range := data["destination_port_range"].(string) - source_address_prefix := data["source_address_prefix"].(string) - destination_address_prefix := data["destination_address_prefix"].(string) - priority := data["priority"].(int) - - properties := network.SecurityRulePropertiesFormat{ - SourcePortRange: &source_port_range, - DestinationPortRange: &destination_port_range, - SourceAddressPrefix: &source_address_prefix, - DestinationAddressPrefix: &destination_address_prefix, - Priority: &priority, - Access: network.SecurityRuleAccess(data["access"].(string)), - Direction: network.SecurityRuleDirection(data["direction"].(string)), - Protocol: network.SecurityRuleProtocol(data["protocol"].(string)), - } - - if v := data["description"].(string); v != "" { - properties.Description = &v - } - - name := data["name"].(string) - rule := network.SecurityRule{ - Name: &name, - Properties: &properties, - } - - rules = append(rules, rule) - } - - return rules, nil -} +//import ( +// "bytes" +// "fmt" +// "log" +// "net/http" +// "time" +// +// "github.com/Azure/azure-sdk-for-go/arm/network" +// "github.com/hashicorp/terraform/helper/hashcode" +// "github.com/hashicorp/terraform/helper/resource" +// "github.com/hashicorp/terraform/helper/schema" +//) +// +//func resourceArmNetworkSecurityGroup() *schema.Resource { +// return &schema.Resource{ +// Create: resourceArmNetworkSecurityGroupCreate, +// Read: resourceArmNetworkSecurityGroupRead, +// Update: resourceArmNetworkSecurityGroupCreate, +// Delete: resourceArmNetworkSecurityGroupDelete, +// +// Schema: map[string]*schema.Schema{ +// "name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// }, +// +// "location": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// StateFunc: azureRMNormalizeLocation, +// }, +// +// "resource_group_name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// }, +// +// "security_rule": &schema.Schema{ +// Type: schema.TypeSet, +// Optional: true, +// Computed: true, +// Elem: &schema.Resource{ +// Schema: map[string]*schema.Schema{ +// "name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "description": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { +// value := v.(string) +// if len(value) > 140 { +// errors = append(errors, fmt.Errorf( +// "The network security rule description can be no longer than 140 chars")) +// } +// return +// }, +// }, +// +// "protocol": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ValidateFunc: validateNetworkSecurityRuleProtocol, +// }, +// +// "source_port_range": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "destination_port_range": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "source_address_prefix": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "destination_address_prefix": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "access": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ValidateFunc: validateNetworkSecurityRuleAccess, +// }, +// +// "priority": &schema.Schema{ +// Type: schema.TypeInt, +// Required: true, +// ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { +// value := v.(int) +// if value < 100 || value > 4096 { +// errors = append(errors, fmt.Errorf( +// "The `priority` can only be between 100 and 4096")) +// } +// return +// }, +// }, +// +// "direction": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ValidateFunc: validateNetworkSecurityRuleDirection, +// }, +// }, +// }, +// Set: resourceArmNetworkSecurityGroupRuleHash, +// }, +// +// "tags": tagsSchema(), +// }, +// } +//} +// +//func resourceArmNetworkSecurityGroupCreate(d *schema.ResourceData, meta interface{}) error { +// client := meta.(*ArmClient) +// secClient := client.secGroupClient +// +// name := d.Get("name").(string) +// location := d.Get("location").(string) +// resGroup := d.Get("resource_group_name").(string) +// tags := d.Get("tags").(map[string]interface{}) +// +// sgRules, sgErr := expandAzureRmSecurityRules(d) +// if sgErr != nil { +// return fmt.Errorf("Error Building list of Network Security Group Rules: %s", sgErr) +// } +// +// sg := network.SecurityGroup{ +// Name: &name, +// Location: &location, +// Properties: &network.SecurityGroupPropertiesFormat{ +// SecurityRules: &sgRules, +// }, +// Tags: expandTags(tags), +// } +// +// resp, err := secClient.CreateOrUpdate(resGroup, name, sg) +// if err != nil { +// return err +// } +// +// d.SetId(*resp.ID) +// +// log.Printf("[DEBUG] Waiting for Network Security Group (%s) to become available", name) +// stateConf := &resource.StateChangeConf{ +// Pending: []string{"Accepted", "Updating"}, +// Target: []string{"Succeeded"}, +// Refresh: securityGroupStateRefreshFunc(client, resGroup, name), +// Timeout: 10 * time.Minute, +// } +// if _, err := stateConf.WaitForState(); err != nil { +// return fmt.Errorf("Error waiting for Network Securty Group (%s) to become available: %s", name, err) +// } +// +// return resourceArmNetworkSecurityGroupRead(d, meta) +//} +// +//func resourceArmNetworkSecurityGroupRead(d *schema.ResourceData, meta interface{}) error { +// secGroupClient := meta.(*ArmClient).secGroupClient +// +// id, err := parseAzureResourceID(d.Id()) +// if err != nil { +// return err +// } +// resGroup := id.ResourceGroup +// name := id.Path["networkSecurityGroups"] +// +// resp, err := secGroupClient.Get(resGroup, name, "") +// if resp.StatusCode == http.StatusNotFound { +// d.SetId("") +// return nil +// } +// if err != nil { +// return fmt.Errorf("Error making Read request on Azure Network Security Group %s: %s", name, err) +// } +// +// if resp.Properties.SecurityRules != nil { +// d.Set("security_rule", flattenNetworkSecurityRules(resp.Properties.SecurityRules)) +// } +// +// flattenAndSetTags(d, resp.Tags) +// +// return nil +//} +// +//func resourceArmNetworkSecurityGroupDelete(d *schema.ResourceData, meta interface{}) error { +// secGroupClient := meta.(*ArmClient).secGroupClient +// +// id, err := parseAzureResourceID(d.Id()) +// if err != nil { +// return err +// } +// resGroup := id.ResourceGroup +// name := id.Path["networkSecurityGroups"] +// +// _, err = secGroupClient.Delete(resGroup, name) +// +// return err +//} +// +//func resourceArmNetworkSecurityGroupRuleHash(v interface{}) int { +// var buf bytes.Buffer +// m := v.(map[string]interface{}) +// buf.WriteString(fmt.Sprintf("%s-", m["protocol"].(string))) +// buf.WriteString(fmt.Sprintf("%s-", m["source_port_range"].(string))) +// buf.WriteString(fmt.Sprintf("%s-", m["destination_port_range"].(string))) +// buf.WriteString(fmt.Sprintf("%s-", m["source_address_prefix"].(string))) +// buf.WriteString(fmt.Sprintf("%s-", m["destination_address_prefix"].(string))) +// buf.WriteString(fmt.Sprintf("%s-", m["access"].(string))) +// buf.WriteString(fmt.Sprintf("%d-", m["priority"].(int))) +// buf.WriteString(fmt.Sprintf("%s-", m["direction"].(string))) +// +// return hashcode.String(buf.String()) +//} +// +//func securityGroupStateRefreshFunc(client *ArmClient, resourceGroupName string, securityGroupName string) resource.StateRefreshFunc { +// return func() (interface{}, string, error) { +// res, err := client.secGroupClient.Get(resourceGroupName, securityGroupName, "") +// if err != nil { +// return nil, "", fmt.Errorf("Error issuing read request in securityGroupStateRefreshFunc to Azure ARM for network security group '%s' (RG: '%s'): %s", securityGroupName, resourceGroupName, err) +// } +// +// return res, *res.Properties.ProvisioningState, nil +// } +//} +// +//func flattenNetworkSecurityRules(rules *[]network.SecurityRule) []map[string]interface{} { +// result := make([]map[string]interface{}, 0, len(*rules)) +// for _, rule := range *rules { +// sgRule := make(map[string]interface{}) +// sgRule["name"] = *rule.Name +// sgRule["destination_address_prefix"] = *rule.Properties.DestinationAddressPrefix +// sgRule["destination_port_range"] = *rule.Properties.DestinationPortRange +// sgRule["source_address_prefix"] = *rule.Properties.SourceAddressPrefix +// sgRule["source_port_range"] = *rule.Properties.SourcePortRange +// sgRule["priority"] = int(*rule.Properties.Priority) +// sgRule["access"] = rule.Properties.Access +// sgRule["direction"] = rule.Properties.Direction +// sgRule["protocol"] = rule.Properties.Protocol +// +// if rule.Properties.Description != nil { +// sgRule["description"] = *rule.Properties.Description +// } +// +// result = append(result, sgRule) +// } +// return result +//} +// +//func expandAzureRmSecurityRules(d *schema.ResourceData) ([]network.SecurityRule, error) { +// sgRules := d.Get("security_rule").(*schema.Set).List() +// rules := make([]network.SecurityRule, 0, len(sgRules)) +// +// for _, sgRaw := range sgRules { +// data := sgRaw.(map[string]interface{}) +// +// source_port_range := data["source_port_range"].(string) +// destination_port_range := data["destination_port_range"].(string) +// source_address_prefix := data["source_address_prefix"].(string) +// destination_address_prefix := data["destination_address_prefix"].(string) +// priority := data["priority"].(int) +// +// properties := network.SecurityRulePropertiesFormat{ +// SourcePortRange: &source_port_range, +// DestinationPortRange: &destination_port_range, +// SourceAddressPrefix: &source_address_prefix, +// DestinationAddressPrefix: &destination_address_prefix, +// Priority: &priority, +// Access: network.SecurityRuleAccess(data["access"].(string)), +// Direction: network.SecurityRuleDirection(data["direction"].(string)), +// Protocol: network.SecurityRuleProtocol(data["protocol"].(string)), +// } +// +// if v := data["description"].(string); v != "" { +// properties.Description = &v +// } +// +// name := data["name"].(string) +// rule := network.SecurityRule{ +// Name: &name, +// Properties: &properties, +// } +// +// rules = append(rules, rule) +// } +// +// return rules, nil +//} diff --git a/builtin/providers/azurerm/resource_arm_network_security_group_test.go b/builtin/providers/azurerm/resource_arm_network_security_group_test.go index 64c4f9944fc3..d05ff88bf094 100644 --- a/builtin/providers/azurerm/resource_arm_network_security_group_test.go +++ b/builtin/providers/azurerm/resource_arm_network_security_group_test.go @@ -1,265 +1,265 @@ package azurerm -import ( - "fmt" - "net/http" - "testing" - - "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/terraform" -) - -func TestAccAzureRMNetworkSecurityGroup_basic(t *testing.T) { - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMNetworkSecurityGroupDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccAzureRMNetworkSecurityGroup_basic, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMNetworkSecurityGroupExists("azurerm_network_security_group.test"), - ), - }, - }, - }) -} - -func TestAccAzureRMNetworkSecurityGroup_withTags(t *testing.T) { - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMNetworkSecurityGroupDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccAzureRMNetworkSecurityGroup_withTags, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMNetworkSecurityGroupExists("azurerm_network_security_group.test"), - resource.TestCheckResourceAttr( - "azurerm_network_security_group.test", "tags.#", "2"), - resource.TestCheckResourceAttr( - "azurerm_network_security_group.test", "tags.environment", "Production"), - resource.TestCheckResourceAttr( - "azurerm_network_security_group.test", "tags.cost_center", "MSFT"), - ), - }, - - resource.TestStep{ - Config: testAccAzureRMNetworkSecurityGroup_withTagsUpdate, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMNetworkSecurityGroupExists("azurerm_network_security_group.test"), - resource.TestCheckResourceAttr( - "azurerm_network_security_group.test", "tags.#", "1"), - resource.TestCheckResourceAttr( - "azurerm_network_security_group.test", "tags.environment", "staging"), - ), - }, - }, - }) -} - -func TestAccAzureRMNetworkSecurityGroup_addingExtraRules(t *testing.T) { - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMNetworkSecurityGroupDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccAzureRMNetworkSecurityGroup_basic, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMNetworkSecurityGroupExists("azurerm_network_security_group.test"), - resource.TestCheckResourceAttr( - "azurerm_network_security_group.test", "security_rule.#", "1"), - ), - }, - - resource.TestStep{ - Config: testAccAzureRMNetworkSecurityGroup_anotherRule, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMNetworkSecurityGroupExists("azurerm_network_security_group.test"), - resource.TestCheckResourceAttr( - "azurerm_network_security_group.test", "security_rule.#", "2"), - ), - }, - }, - }) -} - -func testCheckAzureRMNetworkSecurityGroupExists(name string) resource.TestCheckFunc { - return func(s *terraform.State) error { - - rs, ok := s.RootModule().Resources[name] - if !ok { - return fmt.Errorf("Not found: %s", name) - } - - sgName := rs.Primary.Attributes["name"] - resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] - if !hasResourceGroup { - return fmt.Errorf("Bad: no resource group found in state for network security group: %s", sgName) - } - - conn := testAccProvider.Meta().(*ArmClient).secGroupClient - - resp, err := conn.Get(resourceGroup, sgName, "") - if err != nil { - return fmt.Errorf("Bad: Get on secGroupClient: %s", err) - } - - if resp.StatusCode == http.StatusNotFound { - return fmt.Errorf("Bad: Network Security Group %q (resource group: %q) does not exist", name, resourceGroup) - } - - return nil - } -} - -func testCheckAzureRMNetworkSecurityGroupDestroy(s *terraform.State) error { - conn := testAccProvider.Meta().(*ArmClient).secGroupClient - - for _, rs := range s.RootModule().Resources { - if rs.Type != "azurerm_network_security_group" { - continue - } - - name := rs.Primary.Attributes["name"] - resourceGroup := rs.Primary.Attributes["resource_group_name"] - - resp, err := conn.Get(resourceGroup, name, "") - - if err != nil { - return nil - } - - if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("Network Security Group still exists:\n%#v", resp.Properties) - } - } - - return nil -} - -var testAccAzureRMNetworkSecurityGroup_basic = ` -resource "azurerm_resource_group" "test" { - name = "acceptanceTestResourceGroup1" - location = "West US" -} - -resource "azurerm_network_security_group" "test" { - name = "acceptanceTestSecurityGroup1" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - - security_rule { - name = "test123" - priority = 100 - direction = "Inbound" - access = "Allow" - protocol = "Tcp" - source_port_range = "*" - destination_port_range = "*" - source_address_prefix = "*" - destination_address_prefix = "*" - } -} -` - -var testAccAzureRMNetworkSecurityGroup_anotherRule = ` -resource "azurerm_resource_group" "test" { - name = "acceptanceTestResourceGroup1" - location = "West US" -} - -resource "azurerm_network_security_group" "test" { - name = "acceptanceTestSecurityGroup1" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - - security_rule { - name = "test123" - priority = 100 - direction = "Inbound" - access = "Allow" - protocol = "Tcp" - source_port_range = "*" - destination_port_range = "*" - source_address_prefix = "*" - destination_address_prefix = "*" - } - - security_rule { - name = "testDeny" - priority = 101 - direction = "Inbound" - access = "Deny" - protocol = "Udp" - source_port_range = "*" - destination_port_range = "*" - source_address_prefix = "*" - destination_address_prefix = "*" - } -} -` - -var testAccAzureRMNetworkSecurityGroup_withTags = ` -resource "azurerm_resource_group" "test" { - name = "acceptanceTestResourceGroup1" - location = "West US" -} - -resource "azurerm_network_security_group" "test" { - name = "acceptanceTestSecurityGroup1" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - - security_rule { - name = "test123" - priority = 100 - direction = "Inbound" - access = "Allow" - protocol = "Tcp" - source_port_range = "*" - destination_port_range = "*" - source_address_prefix = "*" - destination_address_prefix = "*" - } - - - tags { - environment = "Production" - cost_center = "MSFT" - } -} -` - -var testAccAzureRMNetworkSecurityGroup_withTagsUpdate = ` -resource "azurerm_resource_group" "test" { - name = "acceptanceTestResourceGroup1" - location = "West US" -} - -resource "azurerm_network_security_group" "test" { - name = "acceptanceTestSecurityGroup1" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - - security_rule { - name = "test123" - priority = 100 - direction = "Inbound" - access = "Allow" - protocol = "Tcp" - source_port_range = "*" - destination_port_range = "*" - source_address_prefix = "*" - destination_address_prefix = "*" - } - - tags { - environment = "staging" - } -} -` +//import ( +// "fmt" +// "net/http" +// "testing" +// +// "github.com/hashicorp/terraform/helper/resource" +// "github.com/hashicorp/terraform/terraform" +//) +// +//func TestAccAzureRMNetworkSecurityGroup_basic(t *testing.T) { +// +// resource.Test(t, resource.TestCase{ +// PreCheck: func() { testAccPreCheck(t) }, +// Providers: testAccProviders, +// CheckDestroy: testCheckAzureRMNetworkSecurityGroupDestroy, +// Steps: []resource.TestStep{ +// resource.TestStep{ +// Config: testAccAzureRMNetworkSecurityGroup_basic, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMNetworkSecurityGroupExists("azurerm_network_security_group.test"), +// ), +// }, +// }, +// }) +//} +// +//func TestAccAzureRMNetworkSecurityGroup_withTags(t *testing.T) { +// +// resource.Test(t, resource.TestCase{ +// PreCheck: func() { testAccPreCheck(t) }, +// Providers: testAccProviders, +// CheckDestroy: testCheckAzureRMNetworkSecurityGroupDestroy, +// Steps: []resource.TestStep{ +// resource.TestStep{ +// Config: testAccAzureRMNetworkSecurityGroup_withTags, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMNetworkSecurityGroupExists("azurerm_network_security_group.test"), +// resource.TestCheckResourceAttr( +// "azurerm_network_security_group.test", "tags.#", "2"), +// resource.TestCheckResourceAttr( +// "azurerm_network_security_group.test", "tags.environment", "Production"), +// resource.TestCheckResourceAttr( +// "azurerm_network_security_group.test", "tags.cost_center", "MSFT"), +// ), +// }, +// +// resource.TestStep{ +// Config: testAccAzureRMNetworkSecurityGroup_withTagsUpdate, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMNetworkSecurityGroupExists("azurerm_network_security_group.test"), +// resource.TestCheckResourceAttr( +// "azurerm_network_security_group.test", "tags.#", "1"), +// resource.TestCheckResourceAttr( +// "azurerm_network_security_group.test", "tags.environment", "staging"), +// ), +// }, +// }, +// }) +//} +// +//func TestAccAzureRMNetworkSecurityGroup_addingExtraRules(t *testing.T) { +// +// resource.Test(t, resource.TestCase{ +// PreCheck: func() { testAccPreCheck(t) }, +// Providers: testAccProviders, +// CheckDestroy: testCheckAzureRMNetworkSecurityGroupDestroy, +// Steps: []resource.TestStep{ +// resource.TestStep{ +// Config: testAccAzureRMNetworkSecurityGroup_basic, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMNetworkSecurityGroupExists("azurerm_network_security_group.test"), +// resource.TestCheckResourceAttr( +// "azurerm_network_security_group.test", "security_rule.#", "1"), +// ), +// }, +// +// resource.TestStep{ +// Config: testAccAzureRMNetworkSecurityGroup_anotherRule, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMNetworkSecurityGroupExists("azurerm_network_security_group.test"), +// resource.TestCheckResourceAttr( +// "azurerm_network_security_group.test", "security_rule.#", "2"), +// ), +// }, +// }, +// }) +//} +// +//func testCheckAzureRMNetworkSecurityGroupExists(name string) resource.TestCheckFunc { +// return func(s *terraform.State) error { +// +// rs, ok := s.RootModule().Resources[name] +// if !ok { +// return fmt.Errorf("Not found: %s", name) +// } +// +// sgName := rs.Primary.Attributes["name"] +// resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] +// if !hasResourceGroup { +// return fmt.Errorf("Bad: no resource group found in state for network security group: %s", sgName) +// } +// +// conn := testAccProvider.Meta().(*ArmClient).secGroupClient +// +// resp, err := conn.Get(resourceGroup, sgName, "") +// if err != nil { +// return fmt.Errorf("Bad: Get on secGroupClient: %s", err) +// } +// +// if resp.StatusCode == http.StatusNotFound { +// return fmt.Errorf("Bad: Network Security Group %q (resource group: %q) does not exist", name, resourceGroup) +// } +// +// return nil +// } +//} +// +//func testCheckAzureRMNetworkSecurityGroupDestroy(s *terraform.State) error { +// conn := testAccProvider.Meta().(*ArmClient).secGroupClient +// +// for _, rs := range s.RootModule().Resources { +// if rs.Type != "azurerm_network_security_group" { +// continue +// } +// +// name := rs.Primary.Attributes["name"] +// resourceGroup := rs.Primary.Attributes["resource_group_name"] +// +// resp, err := conn.Get(resourceGroup, name, "") +// +// if err != nil { +// return nil +// } +// +// if resp.StatusCode != http.StatusNotFound { +// return fmt.Errorf("Network Security Group still exists:\n%#v", resp.Properties) +// } +// } +// +// return nil +//} +// +//var testAccAzureRMNetworkSecurityGroup_basic = ` +//resource "azurerm_resource_group" "test" { +// name = "acceptanceTestResourceGroup1" +// location = "West US" +//} +// +//resource "azurerm_network_security_group" "test" { +// name = "acceptanceTestSecurityGroup1" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// +// security_rule { +// name = "test123" +// priority = 100 +// direction = "Inbound" +// access = "Allow" +// protocol = "Tcp" +// source_port_range = "*" +// destination_port_range = "*" +// source_address_prefix = "*" +// destination_address_prefix = "*" +// } +//} +//` +// +//var testAccAzureRMNetworkSecurityGroup_anotherRule = ` +//resource "azurerm_resource_group" "test" { +// name = "acceptanceTestResourceGroup1" +// location = "West US" +//} +// +//resource "azurerm_network_security_group" "test" { +// name = "acceptanceTestSecurityGroup1" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// +// security_rule { +// name = "test123" +// priority = 100 +// direction = "Inbound" +// access = "Allow" +// protocol = "Tcp" +// source_port_range = "*" +// destination_port_range = "*" +// source_address_prefix = "*" +// destination_address_prefix = "*" +// } +// +// security_rule { +// name = "testDeny" +// priority = 101 +// direction = "Inbound" +// access = "Deny" +// protocol = "Udp" +// source_port_range = "*" +// destination_port_range = "*" +// source_address_prefix = "*" +// destination_address_prefix = "*" +// } +//} +//` +// +//var testAccAzureRMNetworkSecurityGroup_withTags = ` +//resource "azurerm_resource_group" "test" { +// name = "acceptanceTestResourceGroup1" +// location = "West US" +//} +// +//resource "azurerm_network_security_group" "test" { +// name = "acceptanceTestSecurityGroup1" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// +// security_rule { +// name = "test123" +// priority = 100 +// direction = "Inbound" +// access = "Allow" +// protocol = "Tcp" +// source_port_range = "*" +// destination_port_range = "*" +// source_address_prefix = "*" +// destination_address_prefix = "*" +// } +// +// +// tags { +// environment = "Production" +// cost_center = "MSFT" +// } +//} +//` +// +//var testAccAzureRMNetworkSecurityGroup_withTagsUpdate = ` +//resource "azurerm_resource_group" "test" { +// name = "acceptanceTestResourceGroup1" +// location = "West US" +//} +// +//resource "azurerm_network_security_group" "test" { +// name = "acceptanceTestSecurityGroup1" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// +// security_rule { +// name = "test123" +// priority = 100 +// direction = "Inbound" +// access = "Allow" +// protocol = "Tcp" +// source_port_range = "*" +// destination_port_range = "*" +// source_address_prefix = "*" +// destination_address_prefix = "*" +// } +// +// tags { +// environment = "staging" +// } +//} +//` diff --git a/builtin/providers/azurerm/resource_arm_network_security_rule.go b/builtin/providers/azurerm/resource_arm_network_security_rule.go index 491e331bc097..b155fce6fe4b 100644 --- a/builtin/providers/azurerm/resource_arm_network_security_rule.go +++ b/builtin/providers/azurerm/resource_arm_network_security_rule.go @@ -1,219 +1,219 @@ package azurerm -import ( - "fmt" - "log" - "net/http" - "time" - - "github.com/Azure/azure-sdk-for-go/arm/network" - "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/helper/schema" -) - -func resourceArmNetworkSecurityRule() *schema.Resource { - return &schema.Resource{ - Create: resourceArmNetworkSecurityRuleCreate, - Read: resourceArmNetworkSecurityRuleRead, - Update: resourceArmNetworkSecurityRuleCreate, - Delete: resourceArmNetworkSecurityRuleDelete, - - Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - - "resource_group_name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - - "network_security_group_name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - - "description": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { - value := v.(string) - if len(value) > 140 { - errors = append(errors, fmt.Errorf( - "The network security rule description can be no longer than 140 chars")) - } - return - }, - }, - - "protocol": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ValidateFunc: validateNetworkSecurityRuleProtocol, - }, - - "source_port_range": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - - "destination_port_range": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - - "source_address_prefix": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - - "destination_address_prefix": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - - "access": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ValidateFunc: validateNetworkSecurityRuleAccess, - }, - - "priority": &schema.Schema{ - Type: schema.TypeInt, - Required: true, - ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { - value := v.(int) - if value < 100 || value > 4096 { - errors = append(errors, fmt.Errorf( - "The `priority` can only be between 100 and 4096")) - } - return - }, - }, - - "direction": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ValidateFunc: validateNetworkSecurityRuleDirection, - }, - }, - } -} - -func resourceArmNetworkSecurityRuleCreate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient) - secClient := client.secRuleClient - - name := d.Get("name").(string) - nsgName := d.Get("network_security_group_name").(string) - resGroup := d.Get("resource_group_name").(string) - - source_port_range := d.Get("source_port_range").(string) - destination_port_range := d.Get("destination_port_range").(string) - source_address_prefix := d.Get("source_address_prefix").(string) - destination_address_prefix := d.Get("destination_address_prefix").(string) - priority := d.Get("priority").(int) - access := d.Get("access").(string) - direction := d.Get("direction").(string) - protocol := d.Get("protocol").(string) - - armMutexKV.Lock(nsgName) - defer armMutexKV.Unlock(nsgName) - - properties := network.SecurityRulePropertiesFormat{ - SourcePortRange: &source_port_range, - DestinationPortRange: &destination_port_range, - SourceAddressPrefix: &source_address_prefix, - DestinationAddressPrefix: &destination_address_prefix, - Priority: &priority, - Access: network.SecurityRuleAccess(access), - Direction: network.SecurityRuleDirection(direction), - Protocol: network.SecurityRuleProtocol(protocol), - } - - if v, ok := d.GetOk("description"); ok { - description := v.(string) - properties.Description = &description - } - - sgr := network.SecurityRule{ - Name: &name, - Properties: &properties, - } - - resp, err := secClient.CreateOrUpdate(resGroup, nsgName, name, sgr) - if err != nil { - return err - } - d.SetId(*resp.ID) - - log.Printf("[DEBUG] Waiting for Network Security Rule (%s) to become available", name) - stateConf := &resource.StateChangeConf{ - Pending: []string{"Accepted", "Updating"}, - Target: []string{"Succeeded"}, - Refresh: securityRuleStateRefreshFunc(client, resGroup, nsgName, name), - Timeout: 10 * time.Minute, - } - if _, err := stateConf.WaitForState(); err != nil { - return fmt.Errorf("Error waiting for Network Securty Rule (%s) to become available: %s", name, err) - } - - return resourceArmNetworkSecurityRuleRead(d, meta) -} - -func resourceArmNetworkSecurityRuleRead(d *schema.ResourceData, meta interface{}) error { - secRuleClient := meta.(*ArmClient).secRuleClient - - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - resGroup := id.ResourceGroup - networkSGName := id.Path["networkSecurityGroups"] - sgRuleName := id.Path["securityRules"] - - resp, err := secRuleClient.Get(resGroup, networkSGName, sgRuleName) - if resp.StatusCode == http.StatusNotFound { - d.SetId("") - return nil - } - if err != nil { - return fmt.Errorf("Error making Read request on Azure Network Security Rule %s: %s", sgRuleName, err) - } - - return nil -} - -func resourceArmNetworkSecurityRuleDelete(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient) - secRuleClient := client.secRuleClient - - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - resGroup := id.ResourceGroup - nsgName := id.Path["networkSecurityGroups"] - sgRuleName := id.Path["securityRules"] - - armMutexKV.Lock(nsgName) - defer armMutexKV.Unlock(nsgName) - - _, err = secRuleClient.Delete(resGroup, nsgName, sgRuleName) - - return err -} - -func securityRuleStateRefreshFunc(client *ArmClient, resourceGroupName string, networkSecurityGroupName string, securityRuleName string) resource.StateRefreshFunc { - return func() (interface{}, string, error) { - res, err := client.secRuleClient.Get(resourceGroupName, networkSecurityGroupName, securityRuleName) - if err != nil { - return nil, "", fmt.Errorf("Error issuing read request in securityGroupStateRefreshFunc to Azure ARM for network security rule '%s' (RG: '%s') (NSG: '%s'): %s", securityRuleName, resourceGroupName, networkSecurityGroupName, err) - } - - return res, *res.Properties.ProvisioningState, nil - } -} +//import ( +// "fmt" +// "log" +// "net/http" +// "time" +// +// "github.com/Azure/azure-sdk-for-go/arm/network" +// "github.com/hashicorp/terraform/helper/resource" +// "github.com/hashicorp/terraform/helper/schema" +//) +// +//func resourceArmNetworkSecurityRule() *schema.Resource { +// return &schema.Resource{ +// Create: resourceArmNetworkSecurityRuleCreate, +// Read: resourceArmNetworkSecurityRuleRead, +// Update: resourceArmNetworkSecurityRuleCreate, +// Delete: resourceArmNetworkSecurityRuleDelete, +// +// Schema: map[string]*schema.Schema{ +// "name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// }, +// +// "resource_group_name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// }, +// +// "network_security_group_name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "description": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { +// value := v.(string) +// if len(value) > 140 { +// errors = append(errors, fmt.Errorf( +// "The network security rule description can be no longer than 140 chars")) +// } +// return +// }, +// }, +// +// "protocol": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ValidateFunc: validateNetworkSecurityRuleProtocol, +// }, +// +// "source_port_range": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "destination_port_range": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "source_address_prefix": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "destination_address_prefix": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "access": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ValidateFunc: validateNetworkSecurityRuleAccess, +// }, +// +// "priority": &schema.Schema{ +// Type: schema.TypeInt, +// Required: true, +// ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { +// value := v.(int) +// if value < 100 || value > 4096 { +// errors = append(errors, fmt.Errorf( +// "The `priority` can only be between 100 and 4096")) +// } +// return +// }, +// }, +// +// "direction": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ValidateFunc: validateNetworkSecurityRuleDirection, +// }, +// }, +// } +//} +// +//func resourceArmNetworkSecurityRuleCreate(d *schema.ResourceData, meta interface{}) error { +// client := meta.(*ArmClient) +// secClient := client.secRuleClient +// +// name := d.Get("name").(string) +// nsgName := d.Get("network_security_group_name").(string) +// resGroup := d.Get("resource_group_name").(string) +// +// source_port_range := d.Get("source_port_range").(string) +// destination_port_range := d.Get("destination_port_range").(string) +// source_address_prefix := d.Get("source_address_prefix").(string) +// destination_address_prefix := d.Get("destination_address_prefix").(string) +// priority := d.Get("priority").(int) +// access := d.Get("access").(string) +// direction := d.Get("direction").(string) +// protocol := d.Get("protocol").(string) +// +// armMutexKV.Lock(nsgName) +// defer armMutexKV.Unlock(nsgName) +// +// properties := network.SecurityRulePropertiesFormat{ +// SourcePortRange: &source_port_range, +// DestinationPortRange: &destination_port_range, +// SourceAddressPrefix: &source_address_prefix, +// DestinationAddressPrefix: &destination_address_prefix, +// Priority: &priority, +// Access: network.SecurityRuleAccess(access), +// Direction: network.SecurityRuleDirection(direction), +// Protocol: network.SecurityRuleProtocol(protocol), +// } +// +// if v, ok := d.GetOk("description"); ok { +// description := v.(string) +// properties.Description = &description +// } +// +// sgr := network.SecurityRule{ +// Name: &name, +// Properties: &properties, +// } +// +// resp, err := secClient.CreateOrUpdate(resGroup, nsgName, name, sgr) +// if err != nil { +// return err +// } +// d.SetId(*resp.ID) +// +// log.Printf("[DEBUG] Waiting for Network Security Rule (%s) to become available", name) +// stateConf := &resource.StateChangeConf{ +// Pending: []string{"Accepted", "Updating"}, +// Target: []string{"Succeeded"}, +// Refresh: securityRuleStateRefreshFunc(client, resGroup, nsgName, name), +// Timeout: 10 * time.Minute, +// } +// if _, err := stateConf.WaitForState(); err != nil { +// return fmt.Errorf("Error waiting for Network Securty Rule (%s) to become available: %s", name, err) +// } +// +// return resourceArmNetworkSecurityRuleRead(d, meta) +//} +// +//func resourceArmNetworkSecurityRuleRead(d *schema.ResourceData, meta interface{}) error { +// secRuleClient := meta.(*ArmClient).secRuleClient +// +// id, err := parseAzureResourceID(d.Id()) +// if err != nil { +// return err +// } +// resGroup := id.ResourceGroup +// networkSGName := id.Path["networkSecurityGroups"] +// sgRuleName := id.Path["securityRules"] +// +// resp, err := secRuleClient.Get(resGroup, networkSGName, sgRuleName) +// if resp.StatusCode == http.StatusNotFound { +// d.SetId("") +// return nil +// } +// if err != nil { +// return fmt.Errorf("Error making Read request on Azure Network Security Rule %s: %s", sgRuleName, err) +// } +// +// return nil +//} +// +//func resourceArmNetworkSecurityRuleDelete(d *schema.ResourceData, meta interface{}) error { +// client := meta.(*ArmClient) +// secRuleClient := client.secRuleClient +// +// id, err := parseAzureResourceID(d.Id()) +// if err != nil { +// return err +// } +// resGroup := id.ResourceGroup +// nsgName := id.Path["networkSecurityGroups"] +// sgRuleName := id.Path["securityRules"] +// +// armMutexKV.Lock(nsgName) +// defer armMutexKV.Unlock(nsgName) +// +// _, err = secRuleClient.Delete(resGroup, nsgName, sgRuleName) +// +// return err +//} +// +//func securityRuleStateRefreshFunc(client *ArmClient, resourceGroupName string, networkSecurityGroupName string, securityRuleName string) resource.StateRefreshFunc { +// return func() (interface{}, string, error) { +// res, err := client.secRuleClient.Get(resourceGroupName, networkSecurityGroupName, securityRuleName) +// if err != nil { +// return nil, "", fmt.Errorf("Error issuing read request in securityGroupStateRefreshFunc to Azure ARM for network security rule '%s' (RG: '%s') (NSG: '%s'): %s", securityRuleName, resourceGroupName, networkSecurityGroupName, err) +// } +// +// return res, *res.Properties.ProvisioningState, nil +// } +//} diff --git a/builtin/providers/azurerm/resource_arm_network_security_rule_test.go b/builtin/providers/azurerm/resource_arm_network_security_rule_test.go index b3b9c9d02dc4..114911574ed9 100644 --- a/builtin/providers/azurerm/resource_arm_network_security_rule_test.go +++ b/builtin/providers/azurerm/resource_arm_network_security_rule_test.go @@ -1,203 +1,203 @@ package azurerm -import ( - "fmt" - "net/http" - "testing" - - "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/terraform" -) - -func TestAccAzureRMNetworkSecurityRule_basic(t *testing.T) { - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMNetworkSecurityRuleDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccAzureRMNetworkSecurityRule_basic, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMNetworkSecurityRuleExists("azurerm_network_security_rule.test"), - ), - }, - }, - }) -} - -func TestAccAzureRMNetworkSecurityRule_addingRules(t *testing.T) { - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMNetworkSecurityRuleDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccAzureRMNetworkSecurityRule_updateBasic, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMNetworkSecurityRuleExists("azurerm_network_security_rule.test1"), - ), - }, - - resource.TestStep{ - Config: testAccAzureRMNetworkSecurityRule_updateExtraRule, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMNetworkSecurityRuleExists("azurerm_network_security_rule.test2"), - ), - }, - }, - }) -} - -func testCheckAzureRMNetworkSecurityRuleExists(name string) resource.TestCheckFunc { - return func(s *terraform.State) error { - - rs, ok := s.RootModule().Resources[name] - if !ok { - return fmt.Errorf("Not found: %s", name) - } - - sgName := rs.Primary.Attributes["network_security_group_name"] - sgrName := rs.Primary.Attributes["name"] - resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] - if !hasResourceGroup { - return fmt.Errorf("Bad: no resource group found in state for network security rule: %s", sgName) - } - - conn := testAccProvider.Meta().(*ArmClient).secRuleClient - - resp, err := conn.Get(resourceGroup, sgName, sgrName) - if err != nil { - return fmt.Errorf("Bad: Get on secRuleClient: %s", err) - } - - if resp.StatusCode == http.StatusNotFound { - return fmt.Errorf("Bad: Network Security Rule %q (resource group: %q) (network security group: %q) does not exist", sgrName, sgName, resourceGroup) - } - - return nil - } -} - -func testCheckAzureRMNetworkSecurityRuleDestroy(s *terraform.State) error { - conn := testAccProvider.Meta().(*ArmClient).secRuleClient - - for _, rs := range s.RootModule().Resources { - - if rs.Type != "azurerm_network_security_rule" { - continue - } - - sgName := rs.Primary.Attributes["network_security_group_name"] - sgrName := rs.Primary.Attributes["name"] - resourceGroup := rs.Primary.Attributes["resource_group_name"] - - resp, err := conn.Get(resourceGroup, sgName, sgrName) - - if err != nil { - return nil - } - - if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("Network Security Rule still exists:\n%#v", resp.Properties) - } - } - - return nil -} - -var testAccAzureRMNetworkSecurityRule_basic = ` -resource "azurerm_resource_group" "test" { - name = "acceptanceTestResourceGroup1" - location = "West US" -} - -resource "azurerm_network_security_group" "test" { - name = "acceptanceTestSecurityGroup1" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" -} - -resource "azurerm_network_security_rule" "test" { - name = "test123" - priority = 100 - direction = "Outbound" - access = "Allow" - protocol = "Tcp" - source_port_range = "*" - destination_port_range = "*" - source_address_prefix = "*" - destination_address_prefix = "*" - resource_group_name = "${azurerm_resource_group.test.name}" - network_security_group_name = "${azurerm_network_security_group.test.name}" -} -` - -var testAccAzureRMNetworkSecurityRule_updateBasic = ` -resource "azurerm_resource_group" "test1" { - name = "acceptanceTestResourceGroup2" - location = "West US" -} - -resource "azurerm_network_security_group" "test1" { - name = "acceptanceTestSecurityGroup2" - location = "West US" - resource_group_name = "${azurerm_resource_group.test1.name}" -} - -resource "azurerm_network_security_rule" "test1" { - name = "test123" - priority = 100 - direction = "Outbound" - access = "Allow" - protocol = "Tcp" - source_port_range = "*" - destination_port_range = "*" - source_address_prefix = "*" - destination_address_prefix = "*" - resource_group_name = "${azurerm_resource_group.test1.name}" - network_security_group_name = "${azurerm_network_security_group.test1.name}" -} -` - -var testAccAzureRMNetworkSecurityRule_updateExtraRule = ` -resource "azurerm_resource_group" "test1" { - name = "acceptanceTestResourceGroup2" - location = "West US" -} - -resource "azurerm_network_security_group" "test1" { - name = "acceptanceTestSecurityGroup2" - location = "West US" - resource_group_name = "${azurerm_resource_group.test1.name}" -} - -resource "azurerm_network_security_rule" "test1" { - name = "test123" - priority = 100 - direction = "Outbound" - access = "Allow" - protocol = "Tcp" - source_port_range = "*" - destination_port_range = "*" - source_address_prefix = "*" - destination_address_prefix = "*" - resource_group_name = "${azurerm_resource_group.test1.name}" - network_security_group_name = "${azurerm_network_security_group.test1.name}" -} - -resource "azurerm_network_security_rule" "test2" { - name = "testing456" - priority = 101 - direction = "Inbound" - access = "Deny" - protocol = "Tcp" - source_port_range = "*" - destination_port_range = "*" - source_address_prefix = "*" - destination_address_prefix = "*" - resource_group_name = "${azurerm_resource_group.test1.name}" - network_security_group_name = "${azurerm_network_security_group.test1.name}" -} -` +//import ( +// "fmt" +// "net/http" +// "testing" +// +// "github.com/hashicorp/terraform/helper/resource" +// "github.com/hashicorp/terraform/terraform" +//) +// +//func TestAccAzureRMNetworkSecurityRule_basic(t *testing.T) { +// +// resource.Test(t, resource.TestCase{ +// PreCheck: func() { testAccPreCheck(t) }, +// Providers: testAccProviders, +// CheckDestroy: testCheckAzureRMNetworkSecurityRuleDestroy, +// Steps: []resource.TestStep{ +// resource.TestStep{ +// Config: testAccAzureRMNetworkSecurityRule_basic, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMNetworkSecurityRuleExists("azurerm_network_security_rule.test"), +// ), +// }, +// }, +// }) +//} +// +//func TestAccAzureRMNetworkSecurityRule_addingRules(t *testing.T) { +// +// resource.Test(t, resource.TestCase{ +// PreCheck: func() { testAccPreCheck(t) }, +// Providers: testAccProviders, +// CheckDestroy: testCheckAzureRMNetworkSecurityRuleDestroy, +// Steps: []resource.TestStep{ +// resource.TestStep{ +// Config: testAccAzureRMNetworkSecurityRule_updateBasic, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMNetworkSecurityRuleExists("azurerm_network_security_rule.test1"), +// ), +// }, +// +// resource.TestStep{ +// Config: testAccAzureRMNetworkSecurityRule_updateExtraRule, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMNetworkSecurityRuleExists("azurerm_network_security_rule.test2"), +// ), +// }, +// }, +// }) +//} +// +//func testCheckAzureRMNetworkSecurityRuleExists(name string) resource.TestCheckFunc { +// return func(s *terraform.State) error { +// +// rs, ok := s.RootModule().Resources[name] +// if !ok { +// return fmt.Errorf("Not found: %s", name) +// } +// +// sgName := rs.Primary.Attributes["network_security_group_name"] +// sgrName := rs.Primary.Attributes["name"] +// resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] +// if !hasResourceGroup { +// return fmt.Errorf("Bad: no resource group found in state for network security rule: %s", sgName) +// } +// +// conn := testAccProvider.Meta().(*ArmClient).secRuleClient +// +// resp, err := conn.Get(resourceGroup, sgName, sgrName) +// if err != nil { +// return fmt.Errorf("Bad: Get on secRuleClient: %s", err) +// } +// +// if resp.StatusCode == http.StatusNotFound { +// return fmt.Errorf("Bad: Network Security Rule %q (resource group: %q) (network security group: %q) does not exist", sgrName, sgName, resourceGroup) +// } +// +// return nil +// } +//} +// +//func testCheckAzureRMNetworkSecurityRuleDestroy(s *terraform.State) error { +// conn := testAccProvider.Meta().(*ArmClient).secRuleClient +// +// for _, rs := range s.RootModule().Resources { +// +// if rs.Type != "azurerm_network_security_rule" { +// continue +// } +// +// sgName := rs.Primary.Attributes["network_security_group_name"] +// sgrName := rs.Primary.Attributes["name"] +// resourceGroup := rs.Primary.Attributes["resource_group_name"] +// +// resp, err := conn.Get(resourceGroup, sgName, sgrName) +// +// if err != nil { +// return nil +// } +// +// if resp.StatusCode != http.StatusNotFound { +// return fmt.Errorf("Network Security Rule still exists:\n%#v", resp.Properties) +// } +// } +// +// return nil +//} +// +//var testAccAzureRMNetworkSecurityRule_basic = ` +//resource "azurerm_resource_group" "test" { +// name = "acceptanceTestResourceGroup1" +// location = "West US" +//} +// +//resource "azurerm_network_security_group" "test" { +// name = "acceptanceTestSecurityGroup1" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +//} +// +//resource "azurerm_network_security_rule" "test" { +// name = "test123" +// priority = 100 +// direction = "Outbound" +// access = "Allow" +// protocol = "Tcp" +// source_port_range = "*" +// destination_port_range = "*" +// source_address_prefix = "*" +// destination_address_prefix = "*" +// resource_group_name = "${azurerm_resource_group.test.name}" +// network_security_group_name = "${azurerm_network_security_group.test.name}" +//} +//` +// +//var testAccAzureRMNetworkSecurityRule_updateBasic = ` +//resource "azurerm_resource_group" "test1" { +// name = "acceptanceTestResourceGroup2" +// location = "West US" +//} +// +//resource "azurerm_network_security_group" "test1" { +// name = "acceptanceTestSecurityGroup2" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test1.name}" +//} +// +//resource "azurerm_network_security_rule" "test1" { +// name = "test123" +// priority = 100 +// direction = "Outbound" +// access = "Allow" +// protocol = "Tcp" +// source_port_range = "*" +// destination_port_range = "*" +// source_address_prefix = "*" +// destination_address_prefix = "*" +// resource_group_name = "${azurerm_resource_group.test1.name}" +// network_security_group_name = "${azurerm_network_security_group.test1.name}" +//} +//` +// +//var testAccAzureRMNetworkSecurityRule_updateExtraRule = ` +//resource "azurerm_resource_group" "test1" { +// name = "acceptanceTestResourceGroup2" +// location = "West US" +//} +// +//resource "azurerm_network_security_group" "test1" { +// name = "acceptanceTestSecurityGroup2" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test1.name}" +//} +// +//resource "azurerm_network_security_rule" "test1" { +// name = "test123" +// priority = 100 +// direction = "Outbound" +// access = "Allow" +// protocol = "Tcp" +// source_port_range = "*" +// destination_port_range = "*" +// source_address_prefix = "*" +// destination_address_prefix = "*" +// resource_group_name = "${azurerm_resource_group.test1.name}" +// network_security_group_name = "${azurerm_network_security_group.test1.name}" +//} +// +//resource "azurerm_network_security_rule" "test2" { +// name = "testing456" +// priority = 101 +// direction = "Inbound" +// access = "Deny" +// protocol = "Tcp" +// source_port_range = "*" +// destination_port_range = "*" +// source_address_prefix = "*" +// destination_address_prefix = "*" +// resource_group_name = "${azurerm_resource_group.test1.name}" +// network_security_group_name = "${azurerm_network_security_group.test1.name}" +//} +//` diff --git a/builtin/providers/azurerm/resource_arm_public_ip.go b/builtin/providers/azurerm/resource_arm_public_ip.go index 5b3c8999c6b1..c9011e08c1ef 100644 --- a/builtin/providers/azurerm/resource_arm_public_ip.go +++ b/builtin/providers/azurerm/resource_arm_public_ip.go @@ -1,251 +1,251 @@ package azurerm -import ( - "fmt" - "log" - "net/http" - "regexp" - "strings" - "time" - - "github.com/Azure/azure-sdk-for-go/arm/network" - "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/helper/schema" -) - -func resourceArmPublicIp() *schema.Resource { - return &schema.Resource{ - Create: resourceArmPublicIpCreate, - Read: resourceArmPublicIpRead, - Update: resourceArmPublicIpCreate, - Delete: resourceArmPublicIpDelete, - - Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - - "location": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - StateFunc: azureRMNormalizeLocation, - }, - - "resource_group_name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - - "public_ip_address_allocation": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ValidateFunc: validatePublicIpAllocation, - }, - - "idle_timeout_in_minutes": &schema.Schema{ - Type: schema.TypeInt, - Optional: true, - ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { - value := v.(int) - if value < 4 || value > 30 { - errors = append(errors, fmt.Errorf( - "The idle timeout must be between 4 and 30 minutes")) - } - return - }, - }, - - "domain_name_label": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - ValidateFunc: validatePublicIpDomainNameLabel, - }, - - "reverse_fqdn": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - }, - - "fqdn": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - }, - - "ip_address": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - }, - - "tags": tagsSchema(), - }, - } -} - -func resourceArmPublicIpCreate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient) - publicIPClient := client.publicIPClient - - log.Printf("[INFO] preparing arguments for Azure ARM Public IP creation.") - - name := d.Get("name").(string) - location := d.Get("location").(string) - resGroup := d.Get("resource_group_name").(string) - tags := d.Get("tags").(map[string]interface{}) - - properties := network.PublicIPAddressPropertiesFormat{ - PublicIPAllocationMethod: network.IPAllocationMethod(d.Get("public_ip_address_allocation").(string)), - } - - dnl, hasDnl := d.GetOk("domain_name_label") - rfqdn, hasRfqdn := d.GetOk("reverse_fqdn") - - if hasDnl || hasRfqdn { - dnsSettings := network.PublicIPAddressDNSSettings{} - - if hasRfqdn { - reverse_fqdn := rfqdn.(string) - dnsSettings.ReverseFqdn = &reverse_fqdn - } - - if hasDnl { - domain_name_label := dnl.(string) - dnsSettings.DomainNameLabel = &domain_name_label - - } - - properties.DNSSettings = &dnsSettings - } - - if v, ok := d.GetOk("idle_timeout_in_minutes"); ok { - idle_timeout := v.(int) - properties.IdleTimeoutInMinutes = &idle_timeout - } - - publicIp := network.PublicIPAddress{ - Name: &name, - Location: &location, - Properties: &properties, - Tags: expandTags(tags), - } - - resp, err := publicIPClient.CreateOrUpdate(resGroup, name, publicIp) - if err != nil { - return err - } - - d.SetId(*resp.ID) - - log.Printf("[DEBUG] Waiting for Public IP (%s) to become available", name) - stateConf := &resource.StateChangeConf{ - Pending: []string{"Accepted", "Updating"}, - Target: []string{"Succeeded"}, - Refresh: publicIPStateRefreshFunc(client, resGroup, name), - Timeout: 10 * time.Minute, - } - if _, err := stateConf.WaitForState(); err != nil { - return fmt.Errorf("Error waiting for Public IP (%s) to become available: %s", name, err) - } - - return resourceArmPublicIpRead(d, meta) -} - -func resourceArmPublicIpRead(d *schema.ResourceData, meta interface{}) error { - publicIPClient := meta.(*ArmClient).publicIPClient - - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - resGroup := id.ResourceGroup - name := id.Path["publicIPAddresses"] - - resp, err := publicIPClient.Get(resGroup, name, "") - if resp.StatusCode == http.StatusNotFound { - d.SetId("") - return nil - } - if err != nil { - return fmt.Errorf("Error making Read request on Azure public ip %s: %s", name, err) - } - - if resp.Properties.DNSSettings != nil && resp.Properties.DNSSettings.Fqdn != nil && *resp.Properties.DNSSettings.Fqdn != "" { - d.Set("fqdn", resp.Properties.DNSSettings.Fqdn) - } - - if resp.Properties.IPAddress != nil && *resp.Properties.IPAddress != "" { - d.Set("ip_address", resp.Properties.IPAddress) - } - - flattenAndSetTags(d, resp.Tags) - - return nil -} - -func resourceArmPublicIpDelete(d *schema.ResourceData, meta interface{}) error { - publicIPClient := meta.(*ArmClient).publicIPClient - - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - resGroup := id.ResourceGroup - name := id.Path["publicIPAddresses"] - - _, err = publicIPClient.Delete(resGroup, name) - - return err -} - -func publicIPStateRefreshFunc(client *ArmClient, resourceGroupName string, publicIpName string) resource.StateRefreshFunc { - return func() (interface{}, string, error) { - res, err := client.publicIPClient.Get(resourceGroupName, publicIpName, "") - if err != nil { - return nil, "", fmt.Errorf("Error issuing read request in publicIPStateRefreshFunc to Azure ARM for public ip '%s' (RG: '%s'): %s", publicIpName, resourceGroupName, err) - } - - return res, *res.Properties.ProvisioningState, nil - } -} - -func validatePublicIpAllocation(v interface{}, k string) (ws []string, errors []error) { - value := strings.ToLower(v.(string)) - allocations := map[string]bool{ - "static": true, - "dynamic": true, - } - - if !allocations[value] { - errors = append(errors, fmt.Errorf("Public IP Allocation can only be Static of Dynamic")) - } - return -} - -func validatePublicIpDomainNameLabel(v interface{}, k string) (ws []string, errors []error) { - value := v.(string) - if !regexp.MustCompile(`^[a-z0-9-]+$`).MatchString(value) { - errors = append(errors, fmt.Errorf( - "only alphanumeric characters and hyphens allowed in %q: %q", - k, value)) - } - - if len(value) > 61 { - errors = append(errors, fmt.Errorf( - "%q cannot be longer than 61 characters: %q", k, value)) - } - - if len(value) == 0 { - errors = append(errors, fmt.Errorf( - "%q cannot be an empty string: %q", k, value)) - } - if regexp.MustCompile(`-$`).MatchString(value) { - errors = append(errors, fmt.Errorf( - "%q cannot end with a hyphen: %q", k, value)) - } - - return - -} +//import ( +// "fmt" +// "log" +// "net/http" +// "regexp" +// "strings" +// "time" +// +// "github.com/Azure/azure-sdk-for-go/arm/network" +// "github.com/hashicorp/terraform/helper/resource" +// "github.com/hashicorp/terraform/helper/schema" +//) +// +//func resourceArmPublicIp() *schema.Resource { +// return &schema.Resource{ +// Create: resourceArmPublicIpCreate, +// Read: resourceArmPublicIpRead, +// Update: resourceArmPublicIpCreate, +// Delete: resourceArmPublicIpDelete, +// +// Schema: map[string]*schema.Schema{ +// "name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// }, +// +// "location": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// StateFunc: azureRMNormalizeLocation, +// }, +// +// "resource_group_name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// }, +// +// "public_ip_address_allocation": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ValidateFunc: validatePublicIpAllocation, +// }, +// +// "idle_timeout_in_minutes": &schema.Schema{ +// Type: schema.TypeInt, +// Optional: true, +// ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { +// value := v.(int) +// if value < 4 || value > 30 { +// errors = append(errors, fmt.Errorf( +// "The idle timeout must be between 4 and 30 minutes")) +// } +// return +// }, +// }, +// +// "domain_name_label": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// ValidateFunc: validatePublicIpDomainNameLabel, +// }, +// +// "reverse_fqdn": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// }, +// +// "fqdn": &schema.Schema{ +// Type: schema.TypeString, +// Computed: true, +// }, +// +// "ip_address": &schema.Schema{ +// Type: schema.TypeString, +// Computed: true, +// }, +// +// "tags": tagsSchema(), +// }, +// } +//} +// +//func resourceArmPublicIpCreate(d *schema.ResourceData, meta interface{}) error { +// client := meta.(*ArmClient) +// publicIPClient := client.publicIPClient +// +// log.Printf("[INFO] preparing arguments for Azure ARM Public IP creation.") +// +// name := d.Get("name").(string) +// location := d.Get("location").(string) +// resGroup := d.Get("resource_group_name").(string) +// tags := d.Get("tags").(map[string]interface{}) +// +// properties := network.PublicIPAddressPropertiesFormat{ +// PublicIPAllocationMethod: network.IPAllocationMethod(d.Get("public_ip_address_allocation").(string)), +// } +// +// dnl, hasDnl := d.GetOk("domain_name_label") +// rfqdn, hasRfqdn := d.GetOk("reverse_fqdn") +// +// if hasDnl || hasRfqdn { +// dnsSettings := network.PublicIPAddressDNSSettings{} +// +// if hasRfqdn { +// reverse_fqdn := rfqdn.(string) +// dnsSettings.ReverseFqdn = &reverse_fqdn +// } +// +// if hasDnl { +// domain_name_label := dnl.(string) +// dnsSettings.DomainNameLabel = &domain_name_label +// +// } +// +// properties.DNSSettings = &dnsSettings +// } +// +// if v, ok := d.GetOk("idle_timeout_in_minutes"); ok { +// idle_timeout := v.(int) +// properties.IdleTimeoutInMinutes = &idle_timeout +// } +// +// publicIp := network.PublicIPAddress{ +// Name: &name, +// Location: &location, +// Properties: &properties, +// Tags: expandTags(tags), +// } +// +// resp, err := publicIPClient.CreateOrUpdate(resGroup, name, publicIp) +// if err != nil { +// return err +// } +// +// d.SetId(*resp.ID) +// +// log.Printf("[DEBUG] Waiting for Public IP (%s) to become available", name) +// stateConf := &resource.StateChangeConf{ +// Pending: []string{"Accepted", "Updating"}, +// Target: []string{"Succeeded"}, +// Refresh: publicIPStateRefreshFunc(client, resGroup, name), +// Timeout: 10 * time.Minute, +// } +// if _, err := stateConf.WaitForState(); err != nil { +// return fmt.Errorf("Error waiting for Public IP (%s) to become available: %s", name, err) +// } +// +// return resourceArmPublicIpRead(d, meta) +//} +// +//func resourceArmPublicIpRead(d *schema.ResourceData, meta interface{}) error { +// publicIPClient := meta.(*ArmClient).publicIPClient +// +// id, err := parseAzureResourceID(d.Id()) +// if err != nil { +// return err +// } +// resGroup := id.ResourceGroup +// name := id.Path["publicIPAddresses"] +// +// resp, err := publicIPClient.Get(resGroup, name, "") +// if resp.StatusCode == http.StatusNotFound { +// d.SetId("") +// return nil +// } +// if err != nil { +// return fmt.Errorf("Error making Read request on Azure public ip %s: %s", name, err) +// } +// +// if resp.Properties.DNSSettings != nil && resp.Properties.DNSSettings.Fqdn != nil && *resp.Properties.DNSSettings.Fqdn != "" { +// d.Set("fqdn", resp.Properties.DNSSettings.Fqdn) +// } +// +// if resp.Properties.IPAddress != nil && *resp.Properties.IPAddress != "" { +// d.Set("ip_address", resp.Properties.IPAddress) +// } +// +// flattenAndSetTags(d, resp.Tags) +// +// return nil +//} +// +//func resourceArmPublicIpDelete(d *schema.ResourceData, meta interface{}) error { +// publicIPClient := meta.(*ArmClient).publicIPClient +// +// id, err := parseAzureResourceID(d.Id()) +// if err != nil { +// return err +// } +// resGroup := id.ResourceGroup +// name := id.Path["publicIPAddresses"] +// +// _, err = publicIPClient.Delete(resGroup, name) +// +// return err +//} +// +//func publicIPStateRefreshFunc(client *ArmClient, resourceGroupName string, publicIpName string) resource.StateRefreshFunc { +// return func() (interface{}, string, error) { +// res, err := client.publicIPClient.Get(resourceGroupName, publicIpName, "") +// if err != nil { +// return nil, "", fmt.Errorf("Error issuing read request in publicIPStateRefreshFunc to Azure ARM for public ip '%s' (RG: '%s'): %s", publicIpName, resourceGroupName, err) +// } +// +// return res, *res.Properties.ProvisioningState, nil +// } +//} +// +//func validatePublicIpAllocation(v interface{}, k string) (ws []string, errors []error) { +// value := strings.ToLower(v.(string)) +// allocations := map[string]bool{ +// "static": true, +// "dynamic": true, +// } +// +// if !allocations[value] { +// errors = append(errors, fmt.Errorf("Public IP Allocation can only be Static of Dynamic")) +// } +// return +//} +// +//func validatePublicIpDomainNameLabel(v interface{}, k string) (ws []string, errors []error) { +// value := v.(string) +// if !regexp.MustCompile(`^[a-z0-9-]+$`).MatchString(value) { +// errors = append(errors, fmt.Errorf( +// "only alphanumeric characters and hyphens allowed in %q: %q", +// k, value)) +// } +// +// if len(value) > 61 { +// errors = append(errors, fmt.Errorf( +// "%q cannot be longer than 61 characters: %q", k, value)) +// } +// +// if len(value) == 0 { +// errors = append(errors, fmt.Errorf( +// "%q cannot be an empty string: %q", k, value)) +// } +// if regexp.MustCompile(`-$`).MatchString(value) { +// errors = append(errors, fmt.Errorf( +// "%q cannot end with a hyphen: %q", k, value)) +// } +// +// return +// +//} diff --git a/builtin/providers/azurerm/resource_arm_public_ip_test.go b/builtin/providers/azurerm/resource_arm_public_ip_test.go index eaf4a36461dc..bd9f08fd7eb6 100644 --- a/builtin/providers/azurerm/resource_arm_public_ip_test.go +++ b/builtin/providers/azurerm/resource_arm_public_ip_test.go @@ -1,316 +1,316 @@ 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 TestResourceAzureRMPublicIpAllocation_validation(t *testing.T) { - cases := []struct { - Value string - ErrCount int - }{ - { - Value: "Random", - ErrCount: 1, - }, - { - Value: "Static", - ErrCount: 0, - }, - { - Value: "Dynamic", - ErrCount: 0, - }, - { - Value: "STATIC", - ErrCount: 0, - }, - { - Value: "static", - ErrCount: 0, - }, - } - - for _, tc := range cases { - _, errors := validatePublicIpAllocation(tc.Value, "azurerm_public_ip") - - if len(errors) != tc.ErrCount { - t.Fatalf("Expected the Azure RM Public IP allocation to trigger a validation error") - } - } -} - -func TestResourceAzureRMPublicIpDomainNameLabel_validation(t *testing.T) { - cases := []struct { - Value string - ErrCount int - }{ - { - Value: "tEsting123", - ErrCount: 1, - }, - { - Value: "testing123!", - ErrCount: 1, - }, - { - Value: "testing123-", - ErrCount: 1, - }, - { - Value: acctest.RandString(80), - ErrCount: 1, - }, - } - - for _, tc := range cases { - _, errors := validatePublicIpDomainNameLabel(tc.Value, "azurerm_public_ip") - - if len(errors) != tc.ErrCount { - t.Fatalf("Expected the Azure RM Public IP Domain Name Label to trigger a validation error") - } - } -} - -func TestAccAzureRMPublicIpStatic_basic(t *testing.T) { - - ri := acctest.RandInt() - config := fmt.Sprintf(testAccAzureRMVPublicIpStatic_basic, ri, ri) - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMPublicIpDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: config, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMPublicIpExists("azurerm_public_ip.test"), - ), - }, - }, - }) -} - -func TestAccAzureRMPublicIpStatic_withTags(t *testing.T) { - - ri := acctest.RandInt() - preConfig := fmt.Sprintf(testAccAzureRMVPublicIpStatic_withTags, ri, ri) - postConfig := fmt.Sprintf(testAccAzureRMVPublicIpStatic_withTagsUpdate, ri, ri) - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMPublicIpDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: preConfig, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMPublicIpExists("azurerm_public_ip.test"), - resource.TestCheckResourceAttr( - "azurerm_public_ip.test", "tags.#", "2"), - resource.TestCheckResourceAttr( - "azurerm_public_ip.test", "tags.environment", "Production"), - resource.TestCheckResourceAttr( - "azurerm_public_ip.test", "tags.cost_center", "MSFT"), - ), - }, - - resource.TestStep{ - Config: postConfig, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMPublicIpExists("azurerm_public_ip.test"), - resource.TestCheckResourceAttr( - "azurerm_public_ip.test", "tags.#", "1"), - resource.TestCheckResourceAttr( - "azurerm_public_ip.test", "tags.environment", "staging"), - ), - }, - }, - }) -} - -func TestAccAzureRMPublicIpStatic_update(t *testing.T) { - - ri := acctest.RandInt() - preConfig := fmt.Sprintf(testAccAzureRMVPublicIpStatic_basic, ri, ri) - postConfig := fmt.Sprintf(testAccAzureRMVPublicIpStatic_update, ri, ri) - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMPublicIpDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: preConfig, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMPublicIpExists("azurerm_public_ip.test"), - ), - }, - - resource.TestStep{ - Config: postConfig, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMPublicIpExists("azurerm_public_ip.test"), - resource.TestCheckResourceAttr( - "azurerm_public_ip.test", "domain_name_label", "mylabel01"), - ), - }, - }, - }) -} - -func TestAccAzureRMPublicIpDynamic_basic(t *testing.T) { - - ri := acctest.RandInt() - config := fmt.Sprintf(testAccAzureRMVPublicIpDynamic_basic, ri, ri) - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMPublicIpDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: config, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMPublicIpExists("azurerm_public_ip.test"), - ), - }, - }, - }) -} - -func testCheckAzureRMPublicIpExists(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) - } - - availSetName := rs.Primary.Attributes["name"] - resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] - if !hasResourceGroup { - return fmt.Errorf("Bad: no resource group found in state for public ip: %s", availSetName) - } - - conn := testAccProvider.Meta().(*ArmClient).publicIPClient - - resp, err := conn.Get(resourceGroup, availSetName, "") - if err != nil { - return fmt.Errorf("Bad: Get on publicIPClient: %s", err) - } - - if resp.StatusCode == http.StatusNotFound { - return fmt.Errorf("Bad: Public IP %q (resource group: %q) does not exist", name, resourceGroup) - } - - return nil - } -} - -func testCheckAzureRMPublicIpDestroy(s *terraform.State) error { - conn := testAccProvider.Meta().(*ArmClient).publicIPClient - - for _, rs := range s.RootModule().Resources { - if rs.Type != "azurerm_public_ip" { - continue - } - - name := rs.Primary.Attributes["name"] - resourceGroup := rs.Primary.Attributes["resource_group_name"] - - resp, err := conn.Get(resourceGroup, name, "") - - if err != nil { - return nil - } - - if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("Public IP still exists:\n%#v", resp.Properties) - } - } - - return nil -} - -var testAccAzureRMVPublicIpStatic_basic = ` -resource "azurerm_resource_group" "test" { - name = "acctestrg-%d" - location = "West US" -} -resource "azurerm_public_ip" "test" { - name = "acctestpublicip-%d" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - public_ip_address_allocation = "static" -} -` - -var testAccAzureRMVPublicIpStatic_update = ` -resource "azurerm_resource_group" "test" { - name = "acctestrg-%d" - location = "West US" -} -resource "azurerm_public_ip" "test" { - name = "acctestpublicip-%d" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - public_ip_address_allocation = "static" - domain_name_label = "mylabel01" -} -` - -var testAccAzureRMVPublicIpDynamic_basic = ` -resource "azurerm_resource_group" "test" { - name = "acctestrg-%d" - location = "West US" -} -resource "azurerm_public_ip" "test" { - name = "acctestpublicip-%d" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - public_ip_address_allocation = "dynamic" -} -` - -var testAccAzureRMVPublicIpStatic_withTags = ` -resource "azurerm_resource_group" "test" { - name = "acctestrg-%d" - location = "West US" -} -resource "azurerm_public_ip" "test" { - name = "acctestpublicip-%d" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - public_ip_address_allocation = "static" - - tags { - environment = "Production" - cost_center = "MSFT" - } -} -` - -var testAccAzureRMVPublicIpStatic_withTagsUpdate = ` -resource "azurerm_resource_group" "test" { - name = "acctestrg-%d" - location = "West US" -} -resource "azurerm_public_ip" "test" { - name = "acctestpublicip-%d" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - public_ip_address_allocation = "static" - - tags { - environment = "staging" - } -} -` +//import ( +// "fmt" +// "net/http" +// "testing" +// +// "github.com/hashicorp/terraform/helper/acctest" +// "github.com/hashicorp/terraform/helper/resource" +// "github.com/hashicorp/terraform/terraform" +//) +// +//func TestResourceAzureRMPublicIpAllocation_validation(t *testing.T) { +// cases := []struct { +// Value string +// ErrCount int +// }{ +// { +// Value: "Random", +// ErrCount: 1, +// }, +// { +// Value: "Static", +// ErrCount: 0, +// }, +// { +// Value: "Dynamic", +// ErrCount: 0, +// }, +// { +// Value: "STATIC", +// ErrCount: 0, +// }, +// { +// Value: "static", +// ErrCount: 0, +// }, +// } +// +// for _, tc := range cases { +// _, errors := validatePublicIpAllocation(tc.Value, "azurerm_public_ip") +// +// if len(errors) != tc.ErrCount { +// t.Fatalf("Expected the Azure RM Public IP allocation to trigger a validation error") +// } +// } +//} +// +//func TestResourceAzureRMPublicIpDomainNameLabel_validation(t *testing.T) { +// cases := []struct { +// Value string +// ErrCount int +// }{ +// { +// Value: "tEsting123", +// ErrCount: 1, +// }, +// { +// Value: "testing123!", +// ErrCount: 1, +// }, +// { +// Value: "testing123-", +// ErrCount: 1, +// }, +// { +// Value: acctest.RandString(80), +// ErrCount: 1, +// }, +// } +// +// for _, tc := range cases { +// _, errors := validatePublicIpDomainNameLabel(tc.Value, "azurerm_public_ip") +// +// if len(errors) != tc.ErrCount { +// t.Fatalf("Expected the Azure RM Public IP Domain Name Label to trigger a validation error") +// } +// } +//} +// +//func TestAccAzureRMPublicIpStatic_basic(t *testing.T) { +// +// ri := acctest.RandInt() +// config := fmt.Sprintf(testAccAzureRMVPublicIpStatic_basic, ri, ri) +// +// resource.Test(t, resource.TestCase{ +// PreCheck: func() { testAccPreCheck(t) }, +// Providers: testAccProviders, +// CheckDestroy: testCheckAzureRMPublicIpDestroy, +// Steps: []resource.TestStep{ +// resource.TestStep{ +// Config: config, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMPublicIpExists("azurerm_public_ip.test"), +// ), +// }, +// }, +// }) +//} +// +//func TestAccAzureRMPublicIpStatic_withTags(t *testing.T) { +// +// ri := acctest.RandInt() +// preConfig := fmt.Sprintf(testAccAzureRMVPublicIpStatic_withTags, ri, ri) +// postConfig := fmt.Sprintf(testAccAzureRMVPublicIpStatic_withTagsUpdate, ri, ri) +// +// resource.Test(t, resource.TestCase{ +// PreCheck: func() { testAccPreCheck(t) }, +// Providers: testAccProviders, +// CheckDestroy: testCheckAzureRMPublicIpDestroy, +// Steps: []resource.TestStep{ +// resource.TestStep{ +// Config: preConfig, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMPublicIpExists("azurerm_public_ip.test"), +// resource.TestCheckResourceAttr( +// "azurerm_public_ip.test", "tags.#", "2"), +// resource.TestCheckResourceAttr( +// "azurerm_public_ip.test", "tags.environment", "Production"), +// resource.TestCheckResourceAttr( +// "azurerm_public_ip.test", "tags.cost_center", "MSFT"), +// ), +// }, +// +// resource.TestStep{ +// Config: postConfig, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMPublicIpExists("azurerm_public_ip.test"), +// resource.TestCheckResourceAttr( +// "azurerm_public_ip.test", "tags.#", "1"), +// resource.TestCheckResourceAttr( +// "azurerm_public_ip.test", "tags.environment", "staging"), +// ), +// }, +// }, +// }) +//} +// +//func TestAccAzureRMPublicIpStatic_update(t *testing.T) { +// +// ri := acctest.RandInt() +// preConfig := fmt.Sprintf(testAccAzureRMVPublicIpStatic_basic, ri, ri) +// postConfig := fmt.Sprintf(testAccAzureRMVPublicIpStatic_update, ri, ri) +// +// resource.Test(t, resource.TestCase{ +// PreCheck: func() { testAccPreCheck(t) }, +// Providers: testAccProviders, +// CheckDestroy: testCheckAzureRMPublicIpDestroy, +// Steps: []resource.TestStep{ +// resource.TestStep{ +// Config: preConfig, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMPublicIpExists("azurerm_public_ip.test"), +// ), +// }, +// +// resource.TestStep{ +// Config: postConfig, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMPublicIpExists("azurerm_public_ip.test"), +// resource.TestCheckResourceAttr( +// "azurerm_public_ip.test", "domain_name_label", "mylabel01"), +// ), +// }, +// }, +// }) +//} +// +//func TestAccAzureRMPublicIpDynamic_basic(t *testing.T) { +// +// ri := acctest.RandInt() +// config := fmt.Sprintf(testAccAzureRMVPublicIpDynamic_basic, ri, ri) +// +// resource.Test(t, resource.TestCase{ +// PreCheck: func() { testAccPreCheck(t) }, +// Providers: testAccProviders, +// CheckDestroy: testCheckAzureRMPublicIpDestroy, +// Steps: []resource.TestStep{ +// resource.TestStep{ +// Config: config, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMPublicIpExists("azurerm_public_ip.test"), +// ), +// }, +// }, +// }) +//} +// +//func testCheckAzureRMPublicIpExists(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) +// } +// +// availSetName := rs.Primary.Attributes["name"] +// resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] +// if !hasResourceGroup { +// return fmt.Errorf("Bad: no resource group found in state for public ip: %s", availSetName) +// } +// +// conn := testAccProvider.Meta().(*ArmClient).publicIPClient +// +// resp, err := conn.Get(resourceGroup, availSetName, "") +// if err != nil { +// return fmt.Errorf("Bad: Get on publicIPClient: %s", err) +// } +// +// if resp.StatusCode == http.StatusNotFound { +// return fmt.Errorf("Bad: Public IP %q (resource group: %q) does not exist", name, resourceGroup) +// } +// +// return nil +// } +//} +// +//func testCheckAzureRMPublicIpDestroy(s *terraform.State) error { +// conn := testAccProvider.Meta().(*ArmClient).publicIPClient +// +// for _, rs := range s.RootModule().Resources { +// if rs.Type != "azurerm_public_ip" { +// continue +// } +// +// name := rs.Primary.Attributes["name"] +// resourceGroup := rs.Primary.Attributes["resource_group_name"] +// +// resp, err := conn.Get(resourceGroup, name, "") +// +// if err != nil { +// return nil +// } +// +// if resp.StatusCode != http.StatusNotFound { +// return fmt.Errorf("Public IP still exists:\n%#v", resp.Properties) +// } +// } +// +// return nil +//} +// +//var testAccAzureRMVPublicIpStatic_basic = ` +//resource "azurerm_resource_group" "test" { +// name = "acctestrg-%d" +// location = "West US" +//} +//resource "azurerm_public_ip" "test" { +// name = "acctestpublicip-%d" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// public_ip_address_allocation = "static" +//} +//` +// +//var testAccAzureRMVPublicIpStatic_update = ` +//resource "azurerm_resource_group" "test" { +// name = "acctestrg-%d" +// location = "West US" +//} +//resource "azurerm_public_ip" "test" { +// name = "acctestpublicip-%d" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// public_ip_address_allocation = "static" +// domain_name_label = "mylabel01" +//} +//` +// +//var testAccAzureRMVPublicIpDynamic_basic = ` +//resource "azurerm_resource_group" "test" { +// name = "acctestrg-%d" +// location = "West US" +//} +//resource "azurerm_public_ip" "test" { +// name = "acctestpublicip-%d" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// public_ip_address_allocation = "dynamic" +//} +//` +// +//var testAccAzureRMVPublicIpStatic_withTags = ` +//resource "azurerm_resource_group" "test" { +// name = "acctestrg-%d" +// location = "West US" +//} +//resource "azurerm_public_ip" "test" { +// name = "acctestpublicip-%d" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// public_ip_address_allocation = "static" +// +// tags { +// environment = "Production" +// cost_center = "MSFT" +// } +//} +//` +// +//var testAccAzureRMVPublicIpStatic_withTagsUpdate = ` +//resource "azurerm_resource_group" "test" { +// name = "acctestrg-%d" +// location = "West US" +//} +//resource "azurerm_public_ip" "test" { +// name = "acctestpublicip-%d" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// public_ip_address_allocation = "static" +// +// tags { +// environment = "staging" +// } +//} +//` diff --git a/builtin/providers/azurerm/resource_arm_route.go b/builtin/providers/azurerm/resource_arm_route.go index ee2b71b35e22..965d7e3a3551 100644 --- a/builtin/providers/azurerm/resource_arm_route.go +++ b/builtin/providers/azurerm/resource_arm_route.go @@ -1,161 +1,161 @@ package azurerm -import ( - "fmt" - "log" - "net/http" - "time" - - "github.com/Azure/azure-sdk-for-go/arm/network" - "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/helper/schema" -) - -func resourceArmRoute() *schema.Resource { - return &schema.Resource{ - Create: resourceArmRouteCreate, - Read: resourceArmRouteRead, - Update: resourceArmRouteCreate, - Delete: resourceArmRouteDelete, - - Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - - "resource_group_name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - - "route_table_name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - - "address_prefix": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - - "next_hop_type": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ValidateFunc: validateRouteTableNextHopType, - }, - - "next_hop_in_ip_address": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Computed: true, - }, - }, - } -} - -func resourceArmRouteCreate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient) - routesClient := client.routesClient - - name := d.Get("name").(string) - rtName := d.Get("route_table_name").(string) - resGroup := d.Get("resource_group_name").(string) - - addressPrefix := d.Get("address_prefix").(string) - nextHopType := d.Get("next_hop_type").(string) - - armMutexKV.Lock(rtName) - defer armMutexKV.Unlock(rtName) - - properties := network.RoutePropertiesFormat{ - AddressPrefix: &addressPrefix, - NextHopType: network.RouteNextHopType(nextHopType), - } - - if v, ok := d.GetOk("next_hop_in_ip_address"); ok { - nextHopInIpAddress := v.(string) - properties.NextHopIPAddress = &nextHopInIpAddress - } - - route := network.Route{ - Name: &name, - Properties: &properties, - } - - resp, err := routesClient.CreateOrUpdate(resGroup, rtName, name, route) - if err != nil { - return err - } - d.SetId(*resp.ID) - - log.Printf("[DEBUG] Waiting for Route (%s) to become available", name) - stateConf := &resource.StateChangeConf{ - Pending: []string{"Accepted", "Updating"}, - Target: []string{"Succeeded"}, - Refresh: routeStateRefreshFunc(client, resGroup, rtName, name), - Timeout: 10 * time.Minute, - } - if _, err := stateConf.WaitForState(); err != nil { - return fmt.Errorf("Error waiting for Route (%s) to become available: %s", name, err) - } - - return resourceArmRouteRead(d, meta) -} - -func resourceArmRouteRead(d *schema.ResourceData, meta interface{}) error { - routesClient := meta.(*ArmClient).routesClient - - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - resGroup := id.ResourceGroup - rtName := id.Path["routeTables"] - routeName := id.Path["routes"] - - resp, err := routesClient.Get(resGroup, rtName, routeName) - if resp.StatusCode == http.StatusNotFound { - d.SetId("") - return nil - } - if err != nil { - return fmt.Errorf("Error making Read request on Azure Route %s: %s", routeName, err) - } - - return nil -} - -func resourceArmRouteDelete(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient) - routesClient := client.routesClient - - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - resGroup := id.ResourceGroup - rtName := id.Path["routeTables"] - routeName := id.Path["routes"] - - armMutexKV.Lock(rtName) - defer armMutexKV.Unlock(rtName) - - _, err = routesClient.Delete(resGroup, rtName, routeName) - - return err -} - -func routeStateRefreshFunc(client *ArmClient, resourceGroupName string, routeTableName string, routeName string) resource.StateRefreshFunc { - return func() (interface{}, string, error) { - res, err := client.routesClient.Get(resourceGroupName, routeTableName, routeName) - if err != nil { - return nil, "", fmt.Errorf("Error issuing read request in routeStateRefreshFunc to Azure ARM for route '%s' (RG: '%s') (NSG: '%s'): %s", routeName, resourceGroupName, routeTableName, err) - } - - return res, *res.Properties.ProvisioningState, nil - } -} +//import ( +// "fmt" +// "log" +// "net/http" +// "time" +// +// "github.com/Azure/azure-sdk-for-go/arm/network" +// "github.com/hashicorp/terraform/helper/resource" +// "github.com/hashicorp/terraform/helper/schema" +//) +// +//func resourceArmRoute() *schema.Resource { +// return &schema.Resource{ +// Create: resourceArmRouteCreate, +// Read: resourceArmRouteRead, +// Update: resourceArmRouteCreate, +// Delete: resourceArmRouteDelete, +// +// Schema: map[string]*schema.Schema{ +// "name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// }, +// +// "resource_group_name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// }, +// +// "route_table_name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// }, +// +// "address_prefix": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "next_hop_type": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ValidateFunc: validateRouteTableNextHopType, +// }, +// +// "next_hop_in_ip_address": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// Computed: true, +// }, +// }, +// } +//} +// +//func resourceArmRouteCreate(d *schema.ResourceData, meta interface{}) error { +// client := meta.(*ArmClient) +// routesClient := client.routesClient +// +// name := d.Get("name").(string) +// rtName := d.Get("route_table_name").(string) +// resGroup := d.Get("resource_group_name").(string) +// +// addressPrefix := d.Get("address_prefix").(string) +// nextHopType := d.Get("next_hop_type").(string) +// +// armMutexKV.Lock(rtName) +// defer armMutexKV.Unlock(rtName) +// +// properties := network.RoutePropertiesFormat{ +// AddressPrefix: &addressPrefix, +// NextHopType: network.RouteNextHopType(nextHopType), +// } +// +// if v, ok := d.GetOk("next_hop_in_ip_address"); ok { +// nextHopInIpAddress := v.(string) +// properties.NextHopIPAddress = &nextHopInIpAddress +// } +// +// route := network.Route{ +// Name: &name, +// Properties: &properties, +// } +// +// resp, err := routesClient.CreateOrUpdate(resGroup, rtName, name, route) +// if err != nil { +// return err +// } +// d.SetId(*resp.ID) +// +// log.Printf("[DEBUG] Waiting for Route (%s) to become available", name) +// stateConf := &resource.StateChangeConf{ +// Pending: []string{"Accepted", "Updating"}, +// Target: []string{"Succeeded"}, +// Refresh: routeStateRefreshFunc(client, resGroup, rtName, name), +// Timeout: 10 * time.Minute, +// } +// if _, err := stateConf.WaitForState(); err != nil { +// return fmt.Errorf("Error waiting for Route (%s) to become available: %s", name, err) +// } +// +// return resourceArmRouteRead(d, meta) +//} +// +//func resourceArmRouteRead(d *schema.ResourceData, meta interface{}) error { +// routesClient := meta.(*ArmClient).routesClient +// +// id, err := parseAzureResourceID(d.Id()) +// if err != nil { +// return err +// } +// resGroup := id.ResourceGroup +// rtName := id.Path["routeTables"] +// routeName := id.Path["routes"] +// +// resp, err := routesClient.Get(resGroup, rtName, routeName) +// if resp.StatusCode == http.StatusNotFound { +// d.SetId("") +// return nil +// } +// if err != nil { +// return fmt.Errorf("Error making Read request on Azure Route %s: %s", routeName, err) +// } +// +// return nil +//} +// +//func resourceArmRouteDelete(d *schema.ResourceData, meta interface{}) error { +// client := meta.(*ArmClient) +// routesClient := client.routesClient +// +// id, err := parseAzureResourceID(d.Id()) +// if err != nil { +// return err +// } +// resGroup := id.ResourceGroup +// rtName := id.Path["routeTables"] +// routeName := id.Path["routes"] +// +// armMutexKV.Lock(rtName) +// defer armMutexKV.Unlock(rtName) +// +// _, err = routesClient.Delete(resGroup, rtName, routeName) +// +// return err +//} +// +//func routeStateRefreshFunc(client *ArmClient, resourceGroupName string, routeTableName string, routeName string) resource.StateRefreshFunc { +// return func() (interface{}, string, error) { +// res, err := client.routesClient.Get(resourceGroupName, routeTableName, routeName) +// if err != nil { +// return nil, "", fmt.Errorf("Error issuing read request in routeStateRefreshFunc to Azure ARM for route '%s' (RG: '%s') (NSG: '%s'): %s", routeName, resourceGroupName, routeTableName, err) +// } +// +// return res, *res.Properties.ProvisioningState, nil +// } +//} diff --git a/builtin/providers/azurerm/resource_arm_route_table.go b/builtin/providers/azurerm/resource_arm_route_table.go index 5e6a663db463..7e6757545927 100644 --- a/builtin/providers/azurerm/resource_arm_route_table.go +++ b/builtin/providers/azurerm/resource_arm_route_table.go @@ -1,258 +1,258 @@ package azurerm -import ( - "bytes" - "fmt" - "log" - "net/http" - "strings" - "time" - - "github.com/Azure/azure-sdk-for-go/arm/network" - "github.com/hashicorp/terraform/helper/hashcode" - "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/helper/schema" -) - -func resourceArmRouteTable() *schema.Resource { - return &schema.Resource{ - Create: resourceArmRouteTableCreate, - Read: resourceArmRouteTableRead, - Update: resourceArmRouteTableCreate, - Delete: resourceArmRouteTableDelete, - - Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - - "location": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - StateFunc: azureRMNormalizeLocation, - }, - - "resource_group_name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - - "route": &schema.Schema{ - Type: schema.TypeSet, - Optional: true, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - - "address_prefix": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - - "next_hop_type": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ValidateFunc: validateRouteTableNextHopType, - }, - - "next_hop_in_ip_address": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Computed: true, - }, - }, - }, - Set: resourceArmRouteTableRouteHash, - }, - - "subnets": &schema.Schema{ - Type: schema.TypeSet, - Optional: true, - Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - - "tags": tagsSchema(), - }, - } -} - -func resourceArmRouteTableCreate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient) - routeTablesClient := client.routeTablesClient - - log.Printf("[INFO] preparing arguments for Azure ARM Route Table creation.") - - name := d.Get("name").(string) - location := d.Get("location").(string) - resGroup := d.Get("resource_group_name").(string) - tags := d.Get("tags").(map[string]interface{}) - - routeSet := network.RouteTable{ - Name: &name, - Location: &location, - Tags: expandTags(tags), - } - - if _, ok := d.GetOk("route"); ok { - properties := network.RouteTablePropertiesFormat{} - routes, routeErr := expandAzureRmRouteTableRoutes(d) - if routeErr != nil { - return fmt.Errorf("Error Building list of Route Table Routes: %s", routeErr) - } - if len(routes) > 0 { - routeSet.Properties = &properties - } - - } - - resp, err := routeTablesClient.CreateOrUpdate(resGroup, name, routeSet) - if err != nil { - return err - } - - d.SetId(*resp.ID) - - log.Printf("[DEBUG] Waiting for Route Table (%s) to become available", name) - stateConf := &resource.StateChangeConf{ - Pending: []string{"Accepted", "Updating"}, - Target: []string{"Succeeded"}, - Refresh: routeTableStateRefreshFunc(client, resGroup, name), - Timeout: 10 * time.Minute, - } - if _, err := stateConf.WaitForState(); err != nil { - return fmt.Errorf("Error waiting forRoute Table (%s) to become available: %s", name, err) - } - - return resourceArmRouteTableRead(d, meta) -} - -func resourceArmRouteTableRead(d *schema.ResourceData, meta interface{}) error { - routeTablesClient := meta.(*ArmClient).routeTablesClient - - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - resGroup := id.ResourceGroup - name := id.Path["routeTables"] - - resp, err := routeTablesClient.Get(resGroup, name, "") - if resp.StatusCode == http.StatusNotFound { - d.SetId("") - return nil - } - if err != nil { - return fmt.Errorf("Error making Read request on Azure Route Table %s: %s", name, err) - } - - if resp.Properties.Subnets != nil { - if len(*resp.Properties.Subnets) > 0 { - subnets := make([]string, 0, len(*resp.Properties.Subnets)) - for _, subnet := range *resp.Properties.Subnets { - id := subnet.ID - subnets = append(subnets, *id) - } - - if err := d.Set("subnets", subnets); err != nil { - return err - } - } - } - - flattenAndSetTags(d, resp.Tags) - - return nil -} - -func resourceArmRouteTableDelete(d *schema.ResourceData, meta interface{}) error { - routeTablesClient := meta.(*ArmClient).routeTablesClient - - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - resGroup := id.ResourceGroup - name := id.Path["routeTables"] - - _, err = routeTablesClient.Delete(resGroup, name) - - return err -} - -func expandAzureRmRouteTableRoutes(d *schema.ResourceData) ([]network.Route, error) { - configs := d.Get("route").(*schema.Set).List() - routes := make([]network.Route, 0, len(configs)) - - for _, configRaw := range configs { - data := configRaw.(map[string]interface{}) - - address_prefix := data["address_prefix"].(string) - next_hop_type := data["next_hop_type"].(string) - - properties := network.RoutePropertiesFormat{ - AddressPrefix: &address_prefix, - NextHopType: network.RouteNextHopType(next_hop_type), - } - - if v := data["next_hop_in_ip_address"].(string); v != "" { - properties.NextHopIPAddress = &v - } - - name := data["name"].(string) - route := network.Route{ - Name: &name, - Properties: &properties, - } - - routes = append(routes, route) - } - - return routes, nil -} - -func routeTableStateRefreshFunc(client *ArmClient, resourceGroupName string, routeTableName string) resource.StateRefreshFunc { - return func() (interface{}, string, error) { - res, err := client.routeTablesClient.Get(resourceGroupName, routeTableName, "") - if err != nil { - return nil, "", fmt.Errorf("Error issuing read request in routeTableStateRefreshFunc to Azure ARM for route table '%s' (RG: '%s'): %s", routeTableName, resourceGroupName, err) - } - - return res, *res.Properties.ProvisioningState, nil - } -} - -func resourceArmRouteTableRouteHash(v interface{}) int { - var buf bytes.Buffer - m := v.(map[string]interface{}) - buf.WriteString(fmt.Sprintf("%s-", m["name"].(string))) - buf.WriteString(fmt.Sprintf("%s-", m["address_prefix"].(string))) - buf.WriteString(fmt.Sprintf("%s-", m["next_hop_type"].(string))) - - return hashcode.String(buf.String()) -} - -func validateRouteTableNextHopType(v interface{}, k string) (ws []string, errors []error) { - value := strings.ToLower(v.(string)) - hopTypes := map[string]bool{ - "virtualnetworkgateway": true, - "vnetlocal": true, - "internet": true, - "virtualappliance": true, - "none": true, - } - - if !hopTypes[value] { - errors = append(errors, fmt.Errorf("Route Table NextHopType Protocol can only be VirtualNetworkGateway, VnetLocal, Internet or VirtualAppliance")) - } - return -} +//import ( +// "bytes" +// "fmt" +// "log" +// "net/http" +// "strings" +// "time" +// +// "github.com/Azure/azure-sdk-for-go/arm/network" +// "github.com/hashicorp/terraform/helper/hashcode" +// "github.com/hashicorp/terraform/helper/resource" +// "github.com/hashicorp/terraform/helper/schema" +//) +// +//func resourceArmRouteTable() *schema.Resource { +// return &schema.Resource{ +// Create: resourceArmRouteTableCreate, +// Read: resourceArmRouteTableRead, +// Update: resourceArmRouteTableCreate, +// Delete: resourceArmRouteTableDelete, +// +// Schema: map[string]*schema.Schema{ +// "name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// }, +// +// "location": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// StateFunc: azureRMNormalizeLocation, +// }, +// +// "resource_group_name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// }, +// +// "route": &schema.Schema{ +// Type: schema.TypeSet, +// Optional: true, +// Computed: true, +// Elem: &schema.Resource{ +// Schema: map[string]*schema.Schema{ +// "name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "address_prefix": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "next_hop_type": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ValidateFunc: validateRouteTableNextHopType, +// }, +// +// "next_hop_in_ip_address": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// Computed: true, +// }, +// }, +// }, +// Set: resourceArmRouteTableRouteHash, +// }, +// +// "subnets": &schema.Schema{ +// Type: schema.TypeSet, +// Optional: true, +// Computed: true, +// Elem: &schema.Schema{Type: schema.TypeString}, +// Set: schema.HashString, +// }, +// +// "tags": tagsSchema(), +// }, +// } +//} +// +//func resourceArmRouteTableCreate(d *schema.ResourceData, meta interface{}) error { +// client := meta.(*ArmClient) +// routeTablesClient := client.routeTablesClient +// +// log.Printf("[INFO] preparing arguments for Azure ARM Route Table creation.") +// +// name := d.Get("name").(string) +// location := d.Get("location").(string) +// resGroup := d.Get("resource_group_name").(string) +// tags := d.Get("tags").(map[string]interface{}) +// +// routeSet := network.RouteTable{ +// Name: &name, +// Location: &location, +// Tags: expandTags(tags), +// } +// +// if _, ok := d.GetOk("route"); ok { +// properties := network.RouteTablePropertiesFormat{} +// routes, routeErr := expandAzureRmRouteTableRoutes(d) +// if routeErr != nil { +// return fmt.Errorf("Error Building list of Route Table Routes: %s", routeErr) +// } +// if len(routes) > 0 { +// routeSet.Properties = &properties +// } +// +// } +// +// resp, err := routeTablesClient.CreateOrUpdate(resGroup, name, routeSet) +// if err != nil { +// return err +// } +// +// d.SetId(*resp.ID) +// +// log.Printf("[DEBUG] Waiting for Route Table (%s) to become available", name) +// stateConf := &resource.StateChangeConf{ +// Pending: []string{"Accepted", "Updating"}, +// Target: []string{"Succeeded"}, +// Refresh: routeTableStateRefreshFunc(client, resGroup, name), +// Timeout: 10 * time.Minute, +// } +// if _, err := stateConf.WaitForState(); err != nil { +// return fmt.Errorf("Error waiting forRoute Table (%s) to become available: %s", name, err) +// } +// +// return resourceArmRouteTableRead(d, meta) +//} +// +//func resourceArmRouteTableRead(d *schema.ResourceData, meta interface{}) error { +// routeTablesClient := meta.(*ArmClient).routeTablesClient +// +// id, err := parseAzureResourceID(d.Id()) +// if err != nil { +// return err +// } +// resGroup := id.ResourceGroup +// name := id.Path["routeTables"] +// +// resp, err := routeTablesClient.Get(resGroup, name, "") +// if resp.StatusCode == http.StatusNotFound { +// d.SetId("") +// return nil +// } +// if err != nil { +// return fmt.Errorf("Error making Read request on Azure Route Table %s: %s", name, err) +// } +// +// if resp.Properties.Subnets != nil { +// if len(*resp.Properties.Subnets) > 0 { +// subnets := make([]string, 0, len(*resp.Properties.Subnets)) +// for _, subnet := range *resp.Properties.Subnets { +// id := subnet.ID +// subnets = append(subnets, *id) +// } +// +// if err := d.Set("subnets", subnets); err != nil { +// return err +// } +// } +// } +// +// flattenAndSetTags(d, resp.Tags) +// +// return nil +//} +// +//func resourceArmRouteTableDelete(d *schema.ResourceData, meta interface{}) error { +// routeTablesClient := meta.(*ArmClient).routeTablesClient +// +// id, err := parseAzureResourceID(d.Id()) +// if err != nil { +// return err +// } +// resGroup := id.ResourceGroup +// name := id.Path["routeTables"] +// +// _, err = routeTablesClient.Delete(resGroup, name) +// +// return err +//} +// +//func expandAzureRmRouteTableRoutes(d *schema.ResourceData) ([]network.Route, error) { +// configs := d.Get("route").(*schema.Set).List() +// routes := make([]network.Route, 0, len(configs)) +// +// for _, configRaw := range configs { +// data := configRaw.(map[string]interface{}) +// +// address_prefix := data["address_prefix"].(string) +// next_hop_type := data["next_hop_type"].(string) +// +// properties := network.RoutePropertiesFormat{ +// AddressPrefix: &address_prefix, +// NextHopType: network.RouteNextHopType(next_hop_type), +// } +// +// if v := data["next_hop_in_ip_address"].(string); v != "" { +// properties.NextHopIPAddress = &v +// } +// +// name := data["name"].(string) +// route := network.Route{ +// Name: &name, +// Properties: &properties, +// } +// +// routes = append(routes, route) +// } +// +// return routes, nil +//} +// +//func routeTableStateRefreshFunc(client *ArmClient, resourceGroupName string, routeTableName string) resource.StateRefreshFunc { +// return func() (interface{}, string, error) { +// res, err := client.routeTablesClient.Get(resourceGroupName, routeTableName, "") +// if err != nil { +// return nil, "", fmt.Errorf("Error issuing read request in routeTableStateRefreshFunc to Azure ARM for route table '%s' (RG: '%s'): %s", routeTableName, resourceGroupName, err) +// } +// +// return res, *res.Properties.ProvisioningState, nil +// } +//} +// +//func resourceArmRouteTableRouteHash(v interface{}) int { +// var buf bytes.Buffer +// m := v.(map[string]interface{}) +// buf.WriteString(fmt.Sprintf("%s-", m["name"].(string))) +// buf.WriteString(fmt.Sprintf("%s-", m["address_prefix"].(string))) +// buf.WriteString(fmt.Sprintf("%s-", m["next_hop_type"].(string))) +// +// return hashcode.String(buf.String()) +//} +// +//func validateRouteTableNextHopType(v interface{}, k string) (ws []string, errors []error) { +// value := strings.ToLower(v.(string)) +// hopTypes := map[string]bool{ +// "virtualnetworkgateway": true, +// "vnetlocal": true, +// "internet": true, +// "virtualappliance": true, +// "none": true, +// } +// +// if !hopTypes[value] { +// errors = append(errors, fmt.Errorf("Route Table NextHopType Protocol can only be VirtualNetworkGateway, VnetLocal, Internet or VirtualAppliance")) +// } +// return +//} diff --git a/builtin/providers/azurerm/resource_arm_route_table_test.go b/builtin/providers/azurerm/resource_arm_route_table_test.go index e6d978246386..92b9d01044d4 100644 --- a/builtin/providers/azurerm/resource_arm_route_table_test.go +++ b/builtin/providers/azurerm/resource_arm_route_table_test.go @@ -1,294 +1,294 @@ 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 TestResourceAzureRMRouteTableNextHopType_validation(t *testing.T) { - cases := []struct { - Value string - ErrCount int - }{ - { - Value: "Random", - ErrCount: 1, - }, - { - Value: "VirtualNetworkGateway", - ErrCount: 0, - }, - { - Value: "VNETLocal", - ErrCount: 0, - }, - { - Value: "Internet", - ErrCount: 0, - }, - { - Value: "VirtualAppliance", - ErrCount: 0, - }, - { - Value: "None", - ErrCount: 0, - }, - { - Value: "VIRTUALNETWORKGATEWAY", - ErrCount: 0, - }, - { - Value: "virtualnetworkgateway", - ErrCount: 0, - }, - } - - for _, tc := range cases { - _, errors := validateRouteTableNextHopType(tc.Value, "azurerm_route_table") - - if len(errors) != tc.ErrCount { - t.Fatalf("Expected the Azure RM Route Table nextHopType to trigger a validation error") - } - } -} - -func TestAccAzureRMRouteTable_basic(t *testing.T) { - - ri := acctest.RandInt() - config := fmt.Sprintf(testAccAzureRMRouteTable_basic, ri, ri) - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMRouteTableDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: config, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMRouteTableExists("azurerm_route_table.test"), - ), - }, - }, - }) -} - -func TestAccAzureRMRouteTable_withTags(t *testing.T) { - - ri := acctest.RandInt() - preConfig := fmt.Sprintf(testAccAzureRMRouteTable_withTags, ri, ri) - postConfig := fmt.Sprintf(testAccAzureRMRouteTable_withTagsUpdate, ri, ri) - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMRouteTableDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: preConfig, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMRouteTableExists("azurerm_route_table.test"), - resource.TestCheckResourceAttr( - "azurerm_route_table.test", "tags.#", "2"), - resource.TestCheckResourceAttr( - "azurerm_route_table.test", "tags.environment", "Production"), - resource.TestCheckResourceAttr( - "azurerm_route_table.test", "tags.cost_center", "MSFT"), - ), - }, - - resource.TestStep{ - Config: postConfig, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMRouteTableExists("azurerm_route_table.test"), - resource.TestCheckResourceAttr( - "azurerm_route_table.test", "tags.#", "1"), - resource.TestCheckResourceAttr( - "azurerm_route_table.test", "tags.environment", "staging"), - ), - }, - }, - }) -} - -func TestAccAzureRMRouteTable_multipleRoutes(t *testing.T) { - - ri := acctest.RandInt() - preConfig := fmt.Sprintf(testAccAzureRMRouteTable_basic, ri, ri) - postConfig := fmt.Sprintf(testAccAzureRMRouteTable_multipleRoutes, ri, ri) - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMRouteTableDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: preConfig, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMRouteTableExists("azurerm_route_table.test"), - resource.TestCheckResourceAttr( - "azurerm_route_table.test", "route.#", "1"), - ), - }, - - resource.TestStep{ - Config: postConfig, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMRouteTableExists("azurerm_route_table.test"), - resource.TestCheckResourceAttr( - "azurerm_route_table.test", "route.#", "2"), - ), - }, - }, - }) -} - -func testCheckAzureRMRouteTableExists(name string) resource.TestCheckFunc { - return func(s *terraform.State) error { - - rs, ok := s.RootModule().Resources[name] - if !ok { - return fmt.Errorf("Not found: %s", name) - } - - name := rs.Primary.Attributes["name"] - resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] - if !hasResourceGroup { - return fmt.Errorf("Bad: no resource group found in state for route table: %s", name) - } - - conn := testAccProvider.Meta().(*ArmClient).routeTablesClient - - resp, err := conn.Get(resourceGroup, name, "") - if err != nil { - return fmt.Errorf("Bad: Get on routeTablesClient: %s", err) - } - - if resp.StatusCode == http.StatusNotFound { - return fmt.Errorf("Bad: Route Table %q (resource group: %q) does not exist", name, resourceGroup) - } - - return nil - } -} - -func testCheckAzureRMRouteTableDestroy(s *terraform.State) error { - conn := testAccProvider.Meta().(*ArmClient).routeTablesClient - - for _, rs := range s.RootModule().Resources { - if rs.Type != "azurerm_route_table" { - continue - } - - name := rs.Primary.Attributes["name"] - resourceGroup := rs.Primary.Attributes["resource_group_name"] - - resp, err := conn.Get(resourceGroup, name, "") - - if err != nil { - return nil - } - - if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("Route Table still exists:\n%#v", resp.Properties) - } - } - - return nil -} - -var testAccAzureRMRouteTable_basic = ` -resource "azurerm_resource_group" "test" { - name = "acctestrg-%d" - location = "West US" -} - -resource "azurerm_route_table" "test" { - name = "acctestrt%d" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - - route { - name = "route1" - address_prefix = "*" - next_hop_type = "internet" - } -} -` - -var testAccAzureRMRouteTable_multipleRoutes = ` -resource "azurerm_resource_group" "test" { - name = "acctestrg-%d" - location = "West US" -} - -resource "azurerm_route_table" "test" { - name = "acctestrt%d" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - - route { - name = "route1" - address_prefix = "*" - next_hop_type = "internet" - } - - route { - name = "route2" - address_prefix = "*" - next_hop_type = "virtualappliance" - } -} -` - -var testAccAzureRMRouteTable_withTags = ` -resource "azurerm_resource_group" "test" { - name = "acctestrg-%d" - location = "West US" -} - -resource "azurerm_route_table" "test" { - name = "acctestrt%d" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - - route { - name = "route1" - address_prefix = "*" - next_hop_type = "internet" - } - - tags { - environment = "Production" - cost_center = "MSFT" - } -} -` - -var testAccAzureRMRouteTable_withTagsUpdate = ` -resource "azurerm_resource_group" "test" { - name = "acctestrg-%d" - location = "West US" -} - -resource "azurerm_route_table" "test" { - name = "acctestrt%d" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - - route { - name = "route1" - address_prefix = "*" - next_hop_type = "internet" - } - - tags { - environment = "staging" - } -} -` +//import ( +// "fmt" +// "net/http" +// "testing" +// +// "github.com/hashicorp/terraform/helper/acctest" +// "github.com/hashicorp/terraform/helper/resource" +// "github.com/hashicorp/terraform/terraform" +//) +// +//func TestResourceAzureRMRouteTableNextHopType_validation(t *testing.T) { +// cases := []struct { +// Value string +// ErrCount int +// }{ +// { +// Value: "Random", +// ErrCount: 1, +// }, +// { +// Value: "VirtualNetworkGateway", +// ErrCount: 0, +// }, +// { +// Value: "VNETLocal", +// ErrCount: 0, +// }, +// { +// Value: "Internet", +// ErrCount: 0, +// }, +// { +// Value: "VirtualAppliance", +// ErrCount: 0, +// }, +// { +// Value: "None", +// ErrCount: 0, +// }, +// { +// Value: "VIRTUALNETWORKGATEWAY", +// ErrCount: 0, +// }, +// { +// Value: "virtualnetworkgateway", +// ErrCount: 0, +// }, +// } +// +// for _, tc := range cases { +// _, errors := validateRouteTableNextHopType(tc.Value, "azurerm_route_table") +// +// if len(errors) != tc.ErrCount { +// t.Fatalf("Expected the Azure RM Route Table nextHopType to trigger a validation error") +// } +// } +//} +// +//func TestAccAzureRMRouteTable_basic(t *testing.T) { +// +// ri := acctest.RandInt() +// config := fmt.Sprintf(testAccAzureRMRouteTable_basic, ri, ri) +// +// resource.Test(t, resource.TestCase{ +// PreCheck: func() { testAccPreCheck(t) }, +// Providers: testAccProviders, +// CheckDestroy: testCheckAzureRMRouteTableDestroy, +// Steps: []resource.TestStep{ +// resource.TestStep{ +// Config: config, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMRouteTableExists("azurerm_route_table.test"), +// ), +// }, +// }, +// }) +//} +// +//func TestAccAzureRMRouteTable_withTags(t *testing.T) { +// +// ri := acctest.RandInt() +// preConfig := fmt.Sprintf(testAccAzureRMRouteTable_withTags, ri, ri) +// postConfig := fmt.Sprintf(testAccAzureRMRouteTable_withTagsUpdate, ri, ri) +// +// resource.Test(t, resource.TestCase{ +// PreCheck: func() { testAccPreCheck(t) }, +// Providers: testAccProviders, +// CheckDestroy: testCheckAzureRMRouteTableDestroy, +// Steps: []resource.TestStep{ +// resource.TestStep{ +// Config: preConfig, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMRouteTableExists("azurerm_route_table.test"), +// resource.TestCheckResourceAttr( +// "azurerm_route_table.test", "tags.#", "2"), +// resource.TestCheckResourceAttr( +// "azurerm_route_table.test", "tags.environment", "Production"), +// resource.TestCheckResourceAttr( +// "azurerm_route_table.test", "tags.cost_center", "MSFT"), +// ), +// }, +// +// resource.TestStep{ +// Config: postConfig, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMRouteTableExists("azurerm_route_table.test"), +// resource.TestCheckResourceAttr( +// "azurerm_route_table.test", "tags.#", "1"), +// resource.TestCheckResourceAttr( +// "azurerm_route_table.test", "tags.environment", "staging"), +// ), +// }, +// }, +// }) +//} +// +//func TestAccAzureRMRouteTable_multipleRoutes(t *testing.T) { +// +// ri := acctest.RandInt() +// preConfig := fmt.Sprintf(testAccAzureRMRouteTable_basic, ri, ri) +// postConfig := fmt.Sprintf(testAccAzureRMRouteTable_multipleRoutes, ri, ri) +// +// resource.Test(t, resource.TestCase{ +// PreCheck: func() { testAccPreCheck(t) }, +// Providers: testAccProviders, +// CheckDestroy: testCheckAzureRMRouteTableDestroy, +// Steps: []resource.TestStep{ +// resource.TestStep{ +// Config: preConfig, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMRouteTableExists("azurerm_route_table.test"), +// resource.TestCheckResourceAttr( +// "azurerm_route_table.test", "route.#", "1"), +// ), +// }, +// +// resource.TestStep{ +// Config: postConfig, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMRouteTableExists("azurerm_route_table.test"), +// resource.TestCheckResourceAttr( +// "azurerm_route_table.test", "route.#", "2"), +// ), +// }, +// }, +// }) +//} +// +//func testCheckAzureRMRouteTableExists(name string) resource.TestCheckFunc { +// return func(s *terraform.State) error { +// +// rs, ok := s.RootModule().Resources[name] +// if !ok { +// return fmt.Errorf("Not found: %s", name) +// } +// +// name := rs.Primary.Attributes["name"] +// resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] +// if !hasResourceGroup { +// return fmt.Errorf("Bad: no resource group found in state for route table: %s", name) +// } +// +// conn := testAccProvider.Meta().(*ArmClient).routeTablesClient +// +// resp, err := conn.Get(resourceGroup, name, "") +// if err != nil { +// return fmt.Errorf("Bad: Get on routeTablesClient: %s", err) +// } +// +// if resp.StatusCode == http.StatusNotFound { +// return fmt.Errorf("Bad: Route Table %q (resource group: %q) does not exist", name, resourceGroup) +// } +// +// return nil +// } +//} +// +//func testCheckAzureRMRouteTableDestroy(s *terraform.State) error { +// conn := testAccProvider.Meta().(*ArmClient).routeTablesClient +// +// for _, rs := range s.RootModule().Resources { +// if rs.Type != "azurerm_route_table" { +// continue +// } +// +// name := rs.Primary.Attributes["name"] +// resourceGroup := rs.Primary.Attributes["resource_group_name"] +// +// resp, err := conn.Get(resourceGroup, name, "") +// +// if err != nil { +// return nil +// } +// +// if resp.StatusCode != http.StatusNotFound { +// return fmt.Errorf("Route Table still exists:\n%#v", resp.Properties) +// } +// } +// +// return nil +//} +// +//var testAccAzureRMRouteTable_basic = ` +//resource "azurerm_resource_group" "test" { +// name = "acctestrg-%d" +// location = "West US" +//} +// +//resource "azurerm_route_table" "test" { +// name = "acctestrt%d" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// +// route { +// name = "route1" +// address_prefix = "*" +// next_hop_type = "internet" +// } +//} +//` +// +//var testAccAzureRMRouteTable_multipleRoutes = ` +//resource "azurerm_resource_group" "test" { +// name = "acctestrg-%d" +// location = "West US" +//} +// +//resource "azurerm_route_table" "test" { +// name = "acctestrt%d" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// +// route { +// name = "route1" +// address_prefix = "*" +// next_hop_type = "internet" +// } +// +// route { +// name = "route2" +// address_prefix = "*" +// next_hop_type = "virtualappliance" +// } +//} +//` +// +//var testAccAzureRMRouteTable_withTags = ` +//resource "azurerm_resource_group" "test" { +// name = "acctestrg-%d" +// location = "West US" +//} +// +//resource "azurerm_route_table" "test" { +// name = "acctestrt%d" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// +// route { +// name = "route1" +// address_prefix = "*" +// next_hop_type = "internet" +// } +// +// tags { +// environment = "Production" +// cost_center = "MSFT" +// } +//} +//` +// +//var testAccAzureRMRouteTable_withTagsUpdate = ` +//resource "azurerm_resource_group" "test" { +// name = "acctestrg-%d" +// location = "West US" +//} +// +//resource "azurerm_route_table" "test" { +// name = "acctestrt%d" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// +// route { +// name = "route1" +// address_prefix = "*" +// next_hop_type = "internet" +// } +// +// tags { +// environment = "staging" +// } +//} +//` diff --git a/builtin/providers/azurerm/resource_arm_route_test.go b/builtin/providers/azurerm/resource_arm_route_test.go index 660564ac7ce5..b98a6302b74a 100644 --- a/builtin/providers/azurerm/resource_arm_route_test.go +++ b/builtin/providers/azurerm/resource_arm_route_test.go @@ -1,159 +1,159 @@ 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 TestAccAzureRMRoute_basic(t *testing.T) { - - ri := acctest.RandInt() - config := fmt.Sprintf(testAccAzureRMRoute_basic, ri, ri, ri) - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMRouteDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: config, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMRouteExists("azurerm_route.test"), - ), - }, - }, - }) -} - -func TestAccAzureRMRoute_multipleRoutes(t *testing.T) { - - ri := acctest.RandInt() - preConfig := fmt.Sprintf(testAccAzureRMRoute_basic, ri, ri, ri) - postConfig := fmt.Sprintf(testAccAzureRMRoute_multipleRoutes, ri, ri, ri) - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMRouteDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: preConfig, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMRouteExists("azurerm_route.test"), - ), - }, - - resource.TestStep{ - Config: postConfig, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMRouteExists("azurerm_route.test1"), - ), - }, - }, - }) -} - -func testCheckAzureRMRouteExists(name string) resource.TestCheckFunc { - return func(s *terraform.State) error { - - rs, ok := s.RootModule().Resources[name] - if !ok { - return fmt.Errorf("Not found: %s", name) - } - - name := rs.Primary.Attributes["name"] - rtName := rs.Primary.Attributes["route_table_name"] - resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] - if !hasResourceGroup { - return fmt.Errorf("Bad: no resource group found in state for route: %s", name) - } - - conn := testAccProvider.Meta().(*ArmClient).routesClient - - resp, err := conn.Get(resourceGroup, rtName, name) - if err != nil { - return fmt.Errorf("Bad: Get on routesClient: %s", err) - } - - if resp.StatusCode == http.StatusNotFound { - return fmt.Errorf("Bad: Route %q (resource group: %q) does not exist", name, resourceGroup) - } - - return nil - } -} - -func testCheckAzureRMRouteDestroy(s *terraform.State) error { - conn := testAccProvider.Meta().(*ArmClient).routesClient - - for _, rs := range s.RootModule().Resources { - if rs.Type != "azurerm_route" { - continue - } - - name := rs.Primary.Attributes["name"] - rtName := rs.Primary.Attributes["route_table_name"] - resourceGroup := rs.Primary.Attributes["resource_group_name"] - - resp, err := conn.Get(resourceGroup, rtName, name) - - if err != nil { - return nil - } - - if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("Route still exists:\n%#v", resp.Properties) - } - } - - return nil -} - -var testAccAzureRMRoute_basic = ` -resource "azurerm_resource_group" "test" { - name = "acctestrg-%d" - location = "West US" -} - -resource "azurerm_route_table" "test" { - name = "acctestrt%d" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" -} - -resource "azurerm_route" "test" { - name = "acctestroute%d" - resource_group_name = "${azurerm_resource_group.test.name}" - route_table_name = "${azurerm_route_table.test.name}" - - address_prefix = "10.1.0.0/16" - next_hop_type = "vnetlocal" -} -` - -var testAccAzureRMRoute_multipleRoutes = ` -resource "azurerm_resource_group" "test" { - name = "acctestrg-%d" - location = "West US" -} - -resource "azurerm_route_table" "test" { - name = "acctestrt%d" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" -} - -resource "azurerm_route" "test1" { - name = "acctestroute%d" - resource_group_name = "${azurerm_resource_group.test.name}" - route_table_name = "${azurerm_route_table.test.name}" - - address_prefix = "10.2.0.0/16" - next_hop_type = "none" -} -` +//import ( +// "fmt" +// "net/http" +// "testing" +// +// "github.com/hashicorp/terraform/helper/acctest" +// "github.com/hashicorp/terraform/helper/resource" +// "github.com/hashicorp/terraform/terraform" +//) +// +//func TestAccAzureRMRoute_basic(t *testing.T) { +// +// ri := acctest.RandInt() +// config := fmt.Sprintf(testAccAzureRMRoute_basic, ri, ri, ri) +// +// resource.Test(t, resource.TestCase{ +// PreCheck: func() { testAccPreCheck(t) }, +// Providers: testAccProviders, +// CheckDestroy: testCheckAzureRMRouteDestroy, +// Steps: []resource.TestStep{ +// resource.TestStep{ +// Config: config, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMRouteExists("azurerm_route.test"), +// ), +// }, +// }, +// }) +//} +// +//func TestAccAzureRMRoute_multipleRoutes(t *testing.T) { +// +// ri := acctest.RandInt() +// preConfig := fmt.Sprintf(testAccAzureRMRoute_basic, ri, ri, ri) +// postConfig := fmt.Sprintf(testAccAzureRMRoute_multipleRoutes, ri, ri, ri) +// +// resource.Test(t, resource.TestCase{ +// PreCheck: func() { testAccPreCheck(t) }, +// Providers: testAccProviders, +// CheckDestroy: testCheckAzureRMRouteDestroy, +// Steps: []resource.TestStep{ +// resource.TestStep{ +// Config: preConfig, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMRouteExists("azurerm_route.test"), +// ), +// }, +// +// resource.TestStep{ +// Config: postConfig, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMRouteExists("azurerm_route.test1"), +// ), +// }, +// }, +// }) +//} +// +//func testCheckAzureRMRouteExists(name string) resource.TestCheckFunc { +// return func(s *terraform.State) error { +// +// rs, ok := s.RootModule().Resources[name] +// if !ok { +// return fmt.Errorf("Not found: %s", name) +// } +// +// name := rs.Primary.Attributes["name"] +// rtName := rs.Primary.Attributes["route_table_name"] +// resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] +// if !hasResourceGroup { +// return fmt.Errorf("Bad: no resource group found in state for route: %s", name) +// } +// +// conn := testAccProvider.Meta().(*ArmClient).routesClient +// +// resp, err := conn.Get(resourceGroup, rtName, name) +// if err != nil { +// return fmt.Errorf("Bad: Get on routesClient: %s", err) +// } +// +// if resp.StatusCode == http.StatusNotFound { +// return fmt.Errorf("Bad: Route %q (resource group: %q) does not exist", name, resourceGroup) +// } +// +// return nil +// } +//} +// +//func testCheckAzureRMRouteDestroy(s *terraform.State) error { +// conn := testAccProvider.Meta().(*ArmClient).routesClient +// +// for _, rs := range s.RootModule().Resources { +// if rs.Type != "azurerm_route" { +// continue +// } +// +// name := rs.Primary.Attributes["name"] +// rtName := rs.Primary.Attributes["route_table_name"] +// resourceGroup := rs.Primary.Attributes["resource_group_name"] +// +// resp, err := conn.Get(resourceGroup, rtName, name) +// +// if err != nil { +// return nil +// } +// +// if resp.StatusCode != http.StatusNotFound { +// return fmt.Errorf("Route still exists:\n%#v", resp.Properties) +// } +// } +// +// return nil +//} +// +//var testAccAzureRMRoute_basic = ` +//resource "azurerm_resource_group" "test" { +// name = "acctestrg-%d" +// location = "West US" +//} +// +//resource "azurerm_route_table" "test" { +// name = "acctestrt%d" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +//} +// +//resource "azurerm_route" "test" { +// name = "acctestroute%d" +// resource_group_name = "${azurerm_resource_group.test.name}" +// route_table_name = "${azurerm_route_table.test.name}" +// +// address_prefix = "10.1.0.0/16" +// next_hop_type = "vnetlocal" +//} +//` +// +//var testAccAzureRMRoute_multipleRoutes = ` +//resource "azurerm_resource_group" "test" { +// name = "acctestrg-%d" +// location = "West US" +//} +// +//resource "azurerm_route_table" "test" { +// name = "acctestrt%d" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +//} +// +//resource "azurerm_route" "test1" { +// name = "acctestroute%d" +// resource_group_name = "${azurerm_resource_group.test.name}" +// route_table_name = "${azurerm_route_table.test.name}" +// +// address_prefix = "10.2.0.0/16" +// next_hop_type = "none" +//} +//` diff --git a/builtin/providers/azurerm/resource_arm_storage_account.go b/builtin/providers/azurerm/resource_arm_storage_account.go index 121ebb7c74cb..059e9165eee8 100644 --- a/builtin/providers/azurerm/resource_arm_storage_account.go +++ b/builtin/providers/azurerm/resource_arm_storage_account.go @@ -1,309 +1,309 @@ package azurerm -import ( - "fmt" - "net/http" - "regexp" - "strings" - - "github.com/Azure/azure-sdk-for-go/arm/storage" - "github.com/hashicorp/terraform/helper/schema" -) - -func resourceArmStorageAccount() *schema.Resource { - return &schema.Resource{ - Create: resourceArmStorageAccountCreate, - Read: resourceArmStorageAccountRead, - Update: resourceArmStorageAccountUpdate, - Delete: resourceArmStorageAccountDelete, - - Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validateArmStorageAccountName, - }, - - "resource_group_name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - - "location": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - StateFunc: azureRMNormalizeLocation, - }, - - "account_type": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ValidateFunc: validateArmStorageAccountType, - }, - - "primary_location": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - }, - - "secondary_location": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - }, - - "primary_blob_endpoint": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - }, - - "secondary_blob_endpoint": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - }, - - "primary_queue_endpoint": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - }, - - "secondary_queue_endpoint": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - }, - - "primary_table_endpoint": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - }, - - "secondary_table_endpoint": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - }, - - // NOTE: The API does not appear to expose a secondary file endpoint - "primary_file_endpoint": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - }, - - "primary_access_key": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - }, - - "secondary_access_key": &schema.Schema{ - Type: schema.TypeString, - Computed: true, - }, - - "tags": tagsSchema(), - }, - } -} - -func resourceArmStorageAccountCreate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient).storageServiceClient - - resourceGroupName := d.Get("resource_group_name").(string) - storageAccountName := d.Get("name").(string) - accountType := d.Get("account_type").(string) - location := d.Get("location").(string) - tags := d.Get("tags").(map[string]interface{}) - - opts := storage.AccountCreateParameters{ - Location: &location, - Properties: &storage.AccountPropertiesCreateParameters{ - AccountType: storage.AccountType(accountType), - }, - Tags: expandTags(tags), - } - - accResp, err := client.Create(resourceGroupName, storageAccountName, opts) - if err != nil { - return fmt.Errorf("Error creating Azure Storage Account '%s': %s", storageAccountName, err) - } - _, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response.Response, http.StatusOK) - if err != nil { - return fmt.Errorf("Error creating Azure Storage Account %q: %s", storageAccountName, err) - } - - // The only way to get the ID back apparently is to read the resource again - account, err := client.GetProperties(resourceGroupName, storageAccountName) - if err != nil { - return fmt.Errorf("Error retrieving Azure Storage Account %q: %s", storageAccountName, err) - } - - d.SetId(*account.ID) - - return resourceArmStorageAccountRead(d, meta) -} - -// resourceArmStorageAccountUpdate is unusual in the ARM API where most resources have a combined -// and idempotent operation for CreateOrUpdate. In particular updating all of the parameters -// available requires a call to Update per parameter... -func resourceArmStorageAccountUpdate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient).storageServiceClient - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - storageAccountName := id.Path["storageAccounts"] - resourceGroupName := id.ResourceGroup - - d.Partial(true) - - if d.HasChange("account_type") { - accountType := d.Get("account_type").(string) - - opts := storage.AccountUpdateParameters{ - Properties: &storage.AccountPropertiesUpdateParameters{ - AccountType: storage.AccountType(accountType), - }, - } - accResp, err := client.Update(resourceGroupName, storageAccountName, opts) - if err != nil { - return fmt.Errorf("Error updating Azure Storage Account type %q: %s", storageAccountName, err) - } - _, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response.Response, http.StatusOK) - if err != nil { - return fmt.Errorf("Error updating Azure Storage Account type %q: %s", storageAccountName, err) - } - - d.SetPartial("account_type") - } - - if d.HasChange("tags") { - tags := d.Get("tags").(map[string]interface{}) - - opts := storage.AccountUpdateParameters{ - Tags: expandTags(tags), - } - accResp, err := client.Update(resourceGroupName, storageAccountName, opts) - if err != nil { - return fmt.Errorf("Error updating Azure Storage Account tags %q: %s", storageAccountName, err) - } - _, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response.Response, http.StatusOK) - if err != nil { - return fmt.Errorf("Error updating Azure Storage Account tags %q: %s", storageAccountName, err) - } - - d.SetPartial("tags") - } - - d.Partial(false) - return nil -} - -func resourceArmStorageAccountRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient).storageServiceClient - - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - name := id.Path["storageAccounts"] - resGroup := id.ResourceGroup - - resp, err := client.GetProperties(resGroup, name) - if err != nil { - if resp.StatusCode == http.StatusNotFound { - d.SetId("") - return nil - } - - return fmt.Errorf("Error reading the state of AzureRM Storage Account %q: %s", name, err) - } - - keys, err := client.ListKeys(resGroup, name) - if err != nil { - return err - } - - d.Set("primary_access_key", keys.Key1) - d.Set("secondary_access_key", keys.Key2) - d.Set("location", resp.Location) - d.Set("account_type", resp.Properties.AccountType) - d.Set("primary_location", resp.Properties.PrimaryLocation) - d.Set("secondary_location", resp.Properties.SecondaryLocation) - - if resp.Properties.PrimaryEndpoints != nil { - d.Set("primary_blob_endpoint", resp.Properties.PrimaryEndpoints.Blob) - d.Set("primary_queue_endpoint", resp.Properties.PrimaryEndpoints.Queue) - d.Set("primary_table_endpoint", resp.Properties.PrimaryEndpoints.Table) - d.Set("primary_file_endpoint", resp.Properties.PrimaryEndpoints.File) - } - - if resp.Properties.SecondaryEndpoints != nil { - if resp.Properties.SecondaryEndpoints.Blob != nil { - d.Set("secondary_blob_endpoint", resp.Properties.SecondaryEndpoints.Blob) - } else { - d.Set("secondary_blob_endpoint", "") - } - if resp.Properties.SecondaryEndpoints.Queue != nil { - d.Set("secondary_queue_endpoint", resp.Properties.SecondaryEndpoints.Queue) - } else { - d.Set("secondary_queue_endpoint", "") - } - if resp.Properties.SecondaryEndpoints.Table != nil { - d.Set("secondary_table_endpoint", resp.Properties.SecondaryEndpoints.Table) - } else { - d.Set("secondary_table_endpoint", "") - } - } - - flattenAndSetTags(d, resp.Tags) - - return nil -} - -func resourceArmStorageAccountDelete(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient).storageServiceClient - - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - name := id.Path["storageAccounts"] - resGroup := id.ResourceGroup - - accResp, err := client.Delete(resGroup, name) - if err != nil { - return fmt.Errorf("Error issuing AzureRM delete request for storage account %q: %s", name, err) - } - _, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response, http.StatusNotFound) - if err != nil { - return fmt.Errorf("Error polling for AzureRM delete request for storage account %q: %s", name, err) - } - - return nil -} - -func validateArmStorageAccountName(v interface{}, k string) (ws []string, es []error) { - input := v.(string) - - if !regexp.MustCompile(`\A([a-z0-9]{3,24})\z`).MatchString(input) { - es = append(es, fmt.Errorf("name can only consist of lowercase letters and numbers, and must be between 3 and 24 characters long")) - } - - return -} - -func validateArmStorageAccountType(v interface{}, k string) (ws []string, es []error) { - validAccountTypes := []string{"standard_lrs", "standard_zrs", - "standard_grs", "standard_ragrs", "premium_lrs"} - - input := strings.ToLower(v.(string)) - - for _, valid := range validAccountTypes { - if valid == input { - return - } - } - - es = append(es, fmt.Errorf("Invalid storage account type %q", input)) - return -} +//import ( +// "fmt" +// "net/http" +// "regexp" +// "strings" +// +// "github.com/Azure/azure-sdk-for-go/arm/storage" +// "github.com/hashicorp/terraform/helper/schema" +//) +// +//func resourceArmStorageAccount() *schema.Resource { +// return &schema.Resource{ +// Create: resourceArmStorageAccountCreate, +// Read: resourceArmStorageAccountRead, +// Update: resourceArmStorageAccountUpdate, +// Delete: resourceArmStorageAccountDelete, +// +// Schema: map[string]*schema.Schema{ +// "name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// ValidateFunc: validateArmStorageAccountName, +// }, +// +// "resource_group_name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// }, +// +// "location": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// StateFunc: azureRMNormalizeLocation, +// }, +// +// "account_type": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ValidateFunc: validateArmStorageAccountType, +// }, +// +// "primary_location": &schema.Schema{ +// Type: schema.TypeString, +// Computed: true, +// }, +// +// "secondary_location": &schema.Schema{ +// Type: schema.TypeString, +// Computed: true, +// }, +// +// "primary_blob_endpoint": &schema.Schema{ +// Type: schema.TypeString, +// Computed: true, +// }, +// +// "secondary_blob_endpoint": &schema.Schema{ +// Type: schema.TypeString, +// Computed: true, +// }, +// +// "primary_queue_endpoint": &schema.Schema{ +// Type: schema.TypeString, +// Computed: true, +// }, +// +// "secondary_queue_endpoint": &schema.Schema{ +// Type: schema.TypeString, +// Computed: true, +// }, +// +// "primary_table_endpoint": &schema.Schema{ +// Type: schema.TypeString, +// Computed: true, +// }, +// +// "secondary_table_endpoint": &schema.Schema{ +// Type: schema.TypeString, +// Computed: true, +// }, +// +// // NOTE: The API does not appear to expose a secondary file endpoint +// "primary_file_endpoint": &schema.Schema{ +// Type: schema.TypeString, +// Computed: true, +// }, +// +// "primary_access_key": &schema.Schema{ +// Type: schema.TypeString, +// Computed: true, +// }, +// +// "secondary_access_key": &schema.Schema{ +// Type: schema.TypeString, +// Computed: true, +// }, +// +// "tags": tagsSchema(), +// }, +// } +//} +// +//func resourceArmStorageAccountCreate(d *schema.ResourceData, meta interface{}) error { +// client := meta.(*ArmClient).storageServiceClient +// +// resourceGroupName := d.Get("resource_group_name").(string) +// storageAccountName := d.Get("name").(string) +// accountType := d.Get("account_type").(string) +// location := d.Get("location").(string) +// tags := d.Get("tags").(map[string]interface{}) +// +// opts := storage.AccountCreateParameters{ +// Location: &location, +// Properties: &storage.AccountPropertiesCreateParameters{ +// AccountType: storage.AccountType(accountType), +// }, +// Tags: expandTags(tags), +// } +// +// accResp, err := client.Create(resourceGroupName, storageAccountName, opts) +// if err != nil { +// return fmt.Errorf("Error creating Azure Storage Account '%s': %s", storageAccountName, err) +// } +// _, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response.Response, http.StatusOK) +// if err != nil { +// return fmt.Errorf("Error creating Azure Storage Account %q: %s", storageAccountName, err) +// } +// +// // The only way to get the ID back apparently is to read the resource again +// account, err := client.GetProperties(resourceGroupName, storageAccountName) +// if err != nil { +// return fmt.Errorf("Error retrieving Azure Storage Account %q: %s", storageAccountName, err) +// } +// +// d.SetId(*account.ID) +// +// return resourceArmStorageAccountRead(d, meta) +//} +// +//// resourceArmStorageAccountUpdate is unusual in the ARM API where most resources have a combined +//// and idempotent operation for CreateOrUpdate. In particular updating all of the parameters +//// available requires a call to Update per parameter... +//func resourceArmStorageAccountUpdate(d *schema.ResourceData, meta interface{}) error { +// client := meta.(*ArmClient).storageServiceClient +// id, err := parseAzureResourceID(d.Id()) +// if err != nil { +// return err +// } +// storageAccountName := id.Path["storageAccounts"] +// resourceGroupName := id.ResourceGroup +// +// d.Partial(true) +// +// if d.HasChange("account_type") { +// accountType := d.Get("account_type").(string) +// +// opts := storage.AccountUpdateParameters{ +// Properties: &storage.AccountPropertiesUpdateParameters{ +// AccountType: storage.AccountType(accountType), +// }, +// } +// accResp, err := client.Update(resourceGroupName, storageAccountName, opts) +// if err != nil { +// return fmt.Errorf("Error updating Azure Storage Account type %q: %s", storageAccountName, err) +// } +// _, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response.Response, http.StatusOK) +// if err != nil { +// return fmt.Errorf("Error updating Azure Storage Account type %q: %s", storageAccountName, err) +// } +// +// d.SetPartial("account_type") +// } +// +// if d.HasChange("tags") { +// tags := d.Get("tags").(map[string]interface{}) +// +// opts := storage.AccountUpdateParameters{ +// Tags: expandTags(tags), +// } +// accResp, err := client.Update(resourceGroupName, storageAccountName, opts) +// if err != nil { +// return fmt.Errorf("Error updating Azure Storage Account tags %q: %s", storageAccountName, err) +// } +// _, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response.Response, http.StatusOK) +// if err != nil { +// return fmt.Errorf("Error updating Azure Storage Account tags %q: %s", storageAccountName, err) +// } +// +// d.SetPartial("tags") +// } +// +// d.Partial(false) +// return nil +//} +// +//func resourceArmStorageAccountRead(d *schema.ResourceData, meta interface{}) error { +// client := meta.(*ArmClient).storageServiceClient +// +// id, err := parseAzureResourceID(d.Id()) +// if err != nil { +// return err +// } +// name := id.Path["storageAccounts"] +// resGroup := id.ResourceGroup +// +// resp, err := client.GetProperties(resGroup, name) +// if err != nil { +// if resp.StatusCode == http.StatusNotFound { +// d.SetId("") +// return nil +// } +// +// return fmt.Errorf("Error reading the state of AzureRM Storage Account %q: %s", name, err) +// } +// +// keys, err := client.ListKeys(resGroup, name) +// if err != nil { +// return err +// } +// +// d.Set("primary_access_key", keys.Key1) +// d.Set("secondary_access_key", keys.Key2) +// d.Set("location", resp.Location) +// d.Set("account_type", resp.Properties.AccountType) +// d.Set("primary_location", resp.Properties.PrimaryLocation) +// d.Set("secondary_location", resp.Properties.SecondaryLocation) +// +// if resp.Properties.PrimaryEndpoints != nil { +// d.Set("primary_blob_endpoint", resp.Properties.PrimaryEndpoints.Blob) +// d.Set("primary_queue_endpoint", resp.Properties.PrimaryEndpoints.Queue) +// d.Set("primary_table_endpoint", resp.Properties.PrimaryEndpoints.Table) +// d.Set("primary_file_endpoint", resp.Properties.PrimaryEndpoints.File) +// } +// +// if resp.Properties.SecondaryEndpoints != nil { +// if resp.Properties.SecondaryEndpoints.Blob != nil { +// d.Set("secondary_blob_endpoint", resp.Properties.SecondaryEndpoints.Blob) +// } else { +// d.Set("secondary_blob_endpoint", "") +// } +// if resp.Properties.SecondaryEndpoints.Queue != nil { +// d.Set("secondary_queue_endpoint", resp.Properties.SecondaryEndpoints.Queue) +// } else { +// d.Set("secondary_queue_endpoint", "") +// } +// if resp.Properties.SecondaryEndpoints.Table != nil { +// d.Set("secondary_table_endpoint", resp.Properties.SecondaryEndpoints.Table) +// } else { +// d.Set("secondary_table_endpoint", "") +// } +// } +// +// flattenAndSetTags(d, resp.Tags) +// +// return nil +//} +// +//func resourceArmStorageAccountDelete(d *schema.ResourceData, meta interface{}) error { +// client := meta.(*ArmClient).storageServiceClient +// +// id, err := parseAzureResourceID(d.Id()) +// if err != nil { +// return err +// } +// name := id.Path["storageAccounts"] +// resGroup := id.ResourceGroup +// +// accResp, err := client.Delete(resGroup, name) +// if err != nil { +// return fmt.Errorf("Error issuing AzureRM delete request for storage account %q: %s", name, err) +// } +// _, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response, http.StatusNotFound) +// if err != nil { +// return fmt.Errorf("Error polling for AzureRM delete request for storage account %q: %s", name, err) +// } +// +// return nil +//} +// +//func validateArmStorageAccountName(v interface{}, k string) (ws []string, es []error) { +// input := v.(string) +// +// if !regexp.MustCompile(`\A([a-z0-9]{3,24})\z`).MatchString(input) { +// es = append(es, fmt.Errorf("name can only consist of lowercase letters and numbers, and must be between 3 and 24 characters long")) +// } +// +// return +//} +// +//func validateArmStorageAccountType(v interface{}, k string) (ws []string, es []error) { +// validAccountTypes := []string{"standard_lrs", "standard_zrs", +// "standard_grs", "standard_ragrs", "premium_lrs"} +// +// input := strings.ToLower(v.(string)) +// +// for _, valid := range validAccountTypes { +// if valid == input { +// return +// } +// } +// +// es = append(es, fmt.Errorf("Invalid storage account type %q", input)) +// return +//} diff --git a/builtin/providers/azurerm/resource_arm_storage_account_test.go b/builtin/providers/azurerm/resource_arm_storage_account_test.go index 6cad5a1f5091..9bcc694f2860 100644 --- a/builtin/providers/azurerm/resource_arm_storage_account_test.go +++ b/builtin/providers/azurerm/resource_arm_storage_account_test.go @@ -1,166 +1,166 @@ package azurerm -import ( - "fmt" - "net/http" - "testing" - - "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/terraform" -) - -func TestValidateArmStorageAccountType(t *testing.T) { - testCases := []struct { - input string - shouldError bool - }{ - {"standard_lrs", false}, - {"invalid", true}, - } - - for _, test := range testCases { - _, es := validateArmStorageAccountType(test.input, "account_type") - - if test.shouldError && len(es) == 0 { - t.Fatalf("Expected validating account_type %q to fail", test.input) - } - } -} - -func TestValidateArmStorageAccountName(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 := validateArmStorageAccountName(test.input, "name") - - if test.shouldError && len(es) == 0 { - t.Fatalf("Expected validating name %q to fail", test.input) - } - } -} - -func TestAccAzureRMStorageAccount_basic(t *testing.T) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMStorageAccountDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: testAccAzureRMStorageAccount_basic, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMStorageAccountExists("azurerm_storage_account.testsa"), - resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "account_type", "Standard_LRS"), - resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "tags.#", "1"), - resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "tags.environment", "production"), - ), - }, - - resource.TestStep{ - Config: testAccAzureRMStorageAccount_update, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMStorageAccountExists("azurerm_storage_account.testsa"), - resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "account_type", "Standard_GRS"), - resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "tags.#", "1"), - resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "tags.environment", "staging"), - ), - }, - }, - }) -} - -func testCheckAzureRMStorageAccountExists(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) - } - - storageAccount := rs.Primary.Attributes["name"] - resourceGroup := rs.Primary.Attributes["resource_group_name"] - - // Ensure resource group exists in API - conn := testAccProvider.Meta().(*ArmClient).storageServiceClient - - resp, err := conn.GetProperties(resourceGroup, storageAccount) - if err != nil { - return fmt.Errorf("Bad: Get on storageServiceClient: %s", err) - } - - if resp.StatusCode == http.StatusNotFound { - return fmt.Errorf("Bad: StorageAccount %q (resource group: %q) does not exist", name, resourceGroup) - } - - return nil - } -} - -func testCheckAzureRMStorageAccountDestroy(s *terraform.State) error { - conn := testAccProvider.Meta().(*ArmClient).storageServiceClient - - for _, rs := range s.RootModule().Resources { - if rs.Type != "azurerm_storage_account" { - continue - } - - name := rs.Primary.Attributes["name"] - resourceGroup := rs.Primary.Attributes["resource_group_name"] - - resp, err := conn.GetProperties(resourceGroup, name) - if err != nil { - return nil - } - - if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("Storage Account still exists:\n%#v", resp.Properties) - } - } - - return nil -} - -var testAccAzureRMStorageAccount_basic = ` -resource "azurerm_resource_group" "testrg" { - name = "testAccAzureRMStorageAccountBasic" - location = "westus" -} - -resource "azurerm_storage_account" "testsa" { - name = "unlikely23exst2acct1435" - resource_group_name = "${azurerm_resource_group.testrg.name}" - - location = "westus" - account_type = "Standard_LRS" - - tags { - environment = "production" - } -}` - -var testAccAzureRMStorageAccount_update = ` -resource "azurerm_resource_group" "testrg" { - name = "testAccAzureRMStorageAccountBasic" - location = "westus" -} - -resource "azurerm_storage_account" "testsa" { - name = "unlikely23exst2acct1435" - resource_group_name = "${azurerm_resource_group.testrg.name}" - - location = "westus" - account_type = "Standard_GRS" - - tags { - environment = "staging" - } -}` +//import ( +// "fmt" +// "net/http" +// "testing" +// +// "github.com/hashicorp/terraform/helper/resource" +// "github.com/hashicorp/terraform/terraform" +//) +// +//func TestValidateArmStorageAccountType(t *testing.T) { +// testCases := []struct { +// input string +// shouldError bool +// }{ +// {"standard_lrs", false}, +// {"invalid", true}, +// } +// +// for _, test := range testCases { +// _, es := validateArmStorageAccountType(test.input, "account_type") +// +// if test.shouldError && len(es) == 0 { +// t.Fatalf("Expected validating account_type %q to fail", test.input) +// } +// } +//} +// +//func TestValidateArmStorageAccountName(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 := validateArmStorageAccountName(test.input, "name") +// +// if test.shouldError && len(es) == 0 { +// t.Fatalf("Expected validating name %q to fail", test.input) +// } +// } +//} +// +//func TestAccAzureRMStorageAccount_basic(t *testing.T) { +// resource.Test(t, resource.TestCase{ +// PreCheck: func() { testAccPreCheck(t) }, +// Providers: testAccProviders, +// CheckDestroy: testCheckAzureRMStorageAccountDestroy, +// Steps: []resource.TestStep{ +// resource.TestStep{ +// Config: testAccAzureRMStorageAccount_basic, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMStorageAccountExists("azurerm_storage_account.testsa"), +// resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "account_type", "Standard_LRS"), +// resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "tags.#", "1"), +// resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "tags.environment", "production"), +// ), +// }, +// +// resource.TestStep{ +// Config: testAccAzureRMStorageAccount_update, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMStorageAccountExists("azurerm_storage_account.testsa"), +// resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "account_type", "Standard_GRS"), +// resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "tags.#", "1"), +// resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "tags.environment", "staging"), +// ), +// }, +// }, +// }) +//} +// +//func testCheckAzureRMStorageAccountExists(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) +// } +// +// storageAccount := rs.Primary.Attributes["name"] +// resourceGroup := rs.Primary.Attributes["resource_group_name"] +// +// // Ensure resource group exists in API +// conn := testAccProvider.Meta().(*ArmClient).storageServiceClient +// +// resp, err := conn.GetProperties(resourceGroup, storageAccount) +// if err != nil { +// return fmt.Errorf("Bad: Get on storageServiceClient: %s", err) +// } +// +// if resp.StatusCode == http.StatusNotFound { +// return fmt.Errorf("Bad: StorageAccount %q (resource group: %q) does not exist", name, resourceGroup) +// } +// +// return nil +// } +//} +// +//func testCheckAzureRMStorageAccountDestroy(s *terraform.State) error { +// conn := testAccProvider.Meta().(*ArmClient).storageServiceClient +// +// for _, rs := range s.RootModule().Resources { +// if rs.Type != "azurerm_storage_account" { +// continue +// } +// +// name := rs.Primary.Attributes["name"] +// resourceGroup := rs.Primary.Attributes["resource_group_name"] +// +// resp, err := conn.GetProperties(resourceGroup, name) +// if err != nil { +// return nil +// } +// +// if resp.StatusCode != http.StatusNotFound { +// return fmt.Errorf("Storage Account still exists:\n%#v", resp.Properties) +// } +// } +// +// return nil +//} +// +//var testAccAzureRMStorageAccount_basic = ` +//resource "azurerm_resource_group" "testrg" { +// name = "testAccAzureRMStorageAccountBasic" +// location = "westus" +//} +// +//resource "azurerm_storage_account" "testsa" { +// name = "unlikely23exst2acct1435" +// resource_group_name = "${azurerm_resource_group.testrg.name}" +// +// location = "westus" +// account_type = "Standard_LRS" +// +// tags { +// environment = "production" +// } +//}` +// +//var testAccAzureRMStorageAccount_update = ` +//resource "azurerm_resource_group" "testrg" { +// name = "testAccAzureRMStorageAccountBasic" +// location = "westus" +//} +// +//resource "azurerm_storage_account" "testsa" { +// name = "unlikely23exst2acct1435" +// resource_group_name = "${azurerm_resource_group.testrg.name}" +// +// location = "westus" +// account_type = "Standard_GRS" +// +// tags { +// environment = "staging" +// } +//}` diff --git a/builtin/providers/azurerm/resource_arm_storage_blob.go b/builtin/providers/azurerm/resource_arm_storage_blob.go index 9889f4398a89..83f3c8382206 100644 --- a/builtin/providers/azurerm/resource_arm_storage_blob.go +++ b/builtin/providers/azurerm/resource_arm_storage_blob.go @@ -16,12 +16,12 @@ func resourceArmStorageBlob() *schema.Resource { Delete: resourceArmStorageBlobDelete, Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ + "name": { Type: schema.TypeString, Required: true, ForceNew: true, }, - "resource_group_name": &schema.Schema{ + "resource_group_name": { Type: schema.TypeString, Required: true, ForceNew: true, @@ -31,25 +31,25 @@ func resourceArmStorageBlob() *schema.Resource { Required: true, ForceNew: true, }, - "storage_container_name": &schema.Schema{ + "storage_container_name": { Type: schema.TypeString, Required: true, ForceNew: true, }, - "type": &schema.Schema{ + "type": { Type: schema.TypeString, Required: true, ForceNew: true, ValidateFunc: validateArmStorageBlobType, }, - "size": &schema.Schema{ + "size": { Type: schema.TypeInt, Optional: true, ForceNew: true, Default: 0, ValidateFunc: validateArmStorageBlobSize, }, - "url": &schema.Schema{ + "url": { Type: schema.TypeString, Computed: true, }, @@ -204,7 +204,7 @@ func resourceArmStorageBlobDelete(d *schema.ResourceData, meta interface{}) erro storageContainerName := d.Get("storage_container_name").(string) log.Printf("[INFO] Deleting storage blob %q", name) - if _, err = blobClient.DeleteBlobIfExists(storageContainerName, name); err != nil { + if _, err = blobClient.DeleteBlobIfExists(storageContainerName, name, map[string]string{}); err != nil { return fmt.Errorf("Error deleting storage blob %q: %s", name, err) } diff --git a/builtin/providers/azurerm/resource_arm_storage_container.go b/builtin/providers/azurerm/resource_arm_storage_container.go index 1e6591e30879..1b3c3bd9b29f 100644 --- a/builtin/providers/azurerm/resource_arm_storage_container.go +++ b/builtin/providers/azurerm/resource_arm_storage_container.go @@ -1,227 +1,227 @@ package azurerm -import ( - "fmt" - "log" - "strings" - - "regexp" - - "github.com/Azure/azure-sdk-for-go/storage" - "github.com/hashicorp/terraform/helper/schema" -) - -func resourceArmStorageContainer() *schema.Resource { - return &schema.Resource{ - Create: resourceArmStorageContainerCreate, - Read: resourceArmStorageContainerRead, - Exists: resourceArmStorageContainerExists, - Delete: resourceArmStorageContainerDelete, - - Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validateArmStorageContainerName, - }, - "resource_group_name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - "storage_account_name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - "container_access_type": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - ForceNew: true, - Default: "private", - ValidateFunc: validateArmStorageContainerAccessType, - }, - "properties": &schema.Schema{ - Type: schema.TypeMap, - Computed: true, - }, - }, - } -} - -//Following the naming convention as laid out in the docs -func validateArmStorageContainerName(v interface{}, k string) (ws []string, errors []error) { - value := v.(string) - if !regexp.MustCompile(`^[0-9a-z-]+$`).MatchString(value) { - errors = append(errors, fmt.Errorf( - "only lowercase alphanumeric characters and hyphens allowed in %q: %q", - k, value)) - } - if len(value) < 3 || len(value) > 63 { - errors = append(errors, fmt.Errorf( - "%q must be between 3 and 63 characters: %q", k, value)) - } - if regexp.MustCompile(`^-`).MatchString(value) { - errors = append(errors, fmt.Errorf( - "%q cannot begin with a hyphen: %q", k, value)) - } - return -} - -func validateArmStorageContainerAccessType(v interface{}, k string) (ws []string, errors []error) { - value := strings.ToLower(v.(string)) - validTypes := map[string]struct{}{ - "private": struct{}{}, - "blob": struct{}{}, - "container": struct{}{}, - } - - if _, ok := validTypes[value]; !ok { - errors = append(errors, fmt.Errorf("Storage container access type %q is invalid, must be %q, %q or %q", value, "private", "blob", "page")) - } - return -} - -func resourceArmStorageContainerCreate(d *schema.ResourceData, meta interface{}) error { - armClient := meta.(*ArmClient) - - resourceGroupName := d.Get("resource_group_name").(string) - storageAccountName := d.Get("storage_account_name").(string) - - blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroupName, storageAccountName) - if err != nil { - return err - } - if !accountExists { - return fmt.Errorf("Storage Account %q Not Found", storageAccountName) - } - - name := d.Get("name").(string) - - var accessType storage.ContainerAccessType - if d.Get("container_access_type").(string) == "private" { - accessType = storage.ContainerAccessType("") - } else { - accessType = storage.ContainerAccessType(d.Get("container_access_type").(string)) - } - - log.Printf("[INFO] Creating container %q in storage account %q.", name, storageAccountName) - _, err = blobClient.CreateContainerIfNotExists(name, accessType) - if err != nil { - return fmt.Errorf("Error creating container %q in storage account %q: %s", name, storageAccountName, err) - } - - d.SetId(name) - return resourceArmStorageContainerRead(d, meta) -} - -// resourceAzureStorageContainerRead does all the necessary API calls to -// read the status of the storage container off Azure. -func resourceArmStorageContainerRead(d *schema.ResourceData, meta interface{}) error { - armClient := meta.(*ArmClient) - - resourceGroupName := d.Get("resource_group_name").(string) - storageAccountName := d.Get("storage_account_name").(string) - - blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroupName, storageAccountName) - if err != nil { - return err - } - if !accountExists { - log.Printf("[DEBUG] Storage account %q not found, removing container %q from state", storageAccountName, d.Id()) - d.SetId("") - return nil - } - - name := d.Get("name").(string) - containers, err := blobClient.ListContainers(storage.ListContainersParameters{ - Prefix: name, - Timeout: 90, - }) - if err != nil { - return fmt.Errorf("Failed to retrieve storage containers in account %q: %s", name, err) - } - - var found bool - for _, cont := range containers.Containers { - if cont.Name == name { - found = true - - props := make(map[string]interface{}) - props["last_modified"] = cont.Properties.LastModified - props["lease_status"] = cont.Properties.LeaseStatus - props["lease_state"] = cont.Properties.LeaseState - props["lease_duration"] = cont.Properties.LeaseDuration - - d.Set("properties", props) - } - } - - if !found { - log.Printf("[INFO] Storage container %q does not exist in account %q, removing from state...", name, storageAccountName) - d.SetId("") - } - - return nil -} - -func resourceArmStorageContainerExists(d *schema.ResourceData, meta interface{}) (bool, error) { - armClient := meta.(*ArmClient) - - resourceGroupName := d.Get("resource_group_name").(string) - storageAccountName := d.Get("storage_account_name").(string) - - blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroupName, storageAccountName) - if err != nil { - return false, err - } - if !accountExists { - log.Printf("[DEBUG] Storage account %q not found, removing container %q from state", storageAccountName, d.Id()) - d.SetId("") - return false, nil - } - - name := d.Get("name").(string) - - log.Printf("[INFO] Checking existence of storage container %q in storage account %q", name, storageAccountName) - exists, err := blobClient.ContainerExists(name) - if err != nil { - return false, fmt.Errorf("Error querying existence of storage container %q in storage account %q: %s", name, storageAccountName, err) - } - - if !exists { - log.Printf("[INFO] Storage container %q does not exist in account %q, removing from state...", name, storageAccountName) - d.SetId("") - } - - return exists, nil -} - -// resourceAzureStorageContainerDelete does all the necessary API calls to -// delete a storage container off Azure. -func resourceArmStorageContainerDelete(d *schema.ResourceData, meta interface{}) error { - armClient := meta.(*ArmClient) - - resourceGroupName := d.Get("resource_group_name").(string) - storageAccountName := d.Get("storage_account_name").(string) - - blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroupName, storageAccountName) - if err != nil { - return err - } - if !accountExists { - log.Printf("[INFO]Storage Account %q doesn't exist so the container won't exist", storageAccountName) - return nil - } - - name := d.Get("name").(string) - - log.Printf("[INFO] Deleting storage container %q in account %q", name, storageAccountName) - if _, err := blobClient.DeleteContainerIfExists(name); err != nil { - return fmt.Errorf("Error deleting storage container %q from storage account %q: %s", name, storageAccountName, err) - } - - d.SetId("") - return nil -} +//import ( +// "fmt" +// "log" +// "strings" +// +// "regexp" +// +// "github.com/Azure/azure-sdk-for-go/storage" +// "github.com/hashicorp/terraform/helper/schema" +//) +// +//func resourceArmStorageContainer() *schema.Resource { +// return &schema.Resource{ +// Create: resourceArmStorageContainerCreate, +// Read: resourceArmStorageContainerRead, +// Exists: resourceArmStorageContainerExists, +// Delete: resourceArmStorageContainerDelete, +// +// Schema: map[string]*schema.Schema{ +// "name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// ValidateFunc: validateArmStorageContainerName, +// }, +// "resource_group_name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// }, +// "storage_account_name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// }, +// "container_access_type": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// ForceNew: true, +// Default: "private", +// ValidateFunc: validateArmStorageContainerAccessType, +// }, +// "properties": &schema.Schema{ +// Type: schema.TypeMap, +// Computed: true, +// }, +// }, +// } +//} +// +////Following the naming convention as laid out in the docs +//func validateArmStorageContainerName(v interface{}, k string) (ws []string, errors []error) { +// value := v.(string) +// if !regexp.MustCompile(`^[0-9a-z-]+$`).MatchString(value) { +// errors = append(errors, fmt.Errorf( +// "only lowercase alphanumeric characters and hyphens allowed in %q: %q", +// k, value)) +// } +// if len(value) < 3 || len(value) > 63 { +// errors = append(errors, fmt.Errorf( +// "%q must be between 3 and 63 characters: %q", k, value)) +// } +// if regexp.MustCompile(`^-`).MatchString(value) { +// errors = append(errors, fmt.Errorf( +// "%q cannot begin with a hyphen: %q", k, value)) +// } +// return +//} +// +//func validateArmStorageContainerAccessType(v interface{}, k string) (ws []string, errors []error) { +// value := strings.ToLower(v.(string)) +// validTypes := map[string]struct{}{ +// "private": struct{}{}, +// "blob": struct{}{}, +// "container": struct{}{}, +// } +// +// if _, ok := validTypes[value]; !ok { +// errors = append(errors, fmt.Errorf("Storage container access type %q is invalid, must be %q, %q or %q", value, "private", "blob", "page")) +// } +// return +//} +// +//func resourceArmStorageContainerCreate(d *schema.ResourceData, meta interface{}) error { +// armClient := meta.(*ArmClient) +// +// resourceGroupName := d.Get("resource_group_name").(string) +// storageAccountName := d.Get("storage_account_name").(string) +// +// blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroupName, storageAccountName) +// if err != nil { +// return err +// } +// if !accountExists { +// return fmt.Errorf("Storage Account %q Not Found", storageAccountName) +// } +// +// name := d.Get("name").(string) +// +// var accessType storage.ContainerAccessType +// if d.Get("container_access_type").(string) == "private" { +// accessType = storage.ContainerAccessType("") +// } else { +// accessType = storage.ContainerAccessType(d.Get("container_access_type").(string)) +// } +// +// log.Printf("[INFO] Creating container %q in storage account %q.", name, storageAccountName) +// _, err = blobClient.CreateContainerIfNotExists(name, accessType) +// if err != nil { +// return fmt.Errorf("Error creating container %q in storage account %q: %s", name, storageAccountName, err) +// } +// +// d.SetId(name) +// return resourceArmStorageContainerRead(d, meta) +//} +// +//// resourceAzureStorageContainerRead does all the necessary API calls to +//// read the status of the storage container off Azure. +//func resourceArmStorageContainerRead(d *schema.ResourceData, meta interface{}) error { +// armClient := meta.(*ArmClient) +// +// resourceGroupName := d.Get("resource_group_name").(string) +// storageAccountName := d.Get("storage_account_name").(string) +// +// blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroupName, storageAccountName) +// if err != nil { +// return err +// } +// if !accountExists { +// log.Printf("[DEBUG] Storage account %q not found, removing container %q from state", storageAccountName, d.Id()) +// d.SetId("") +// return nil +// } +// +// name := d.Get("name").(string) +// containers, err := blobClient.ListContainers(storage.ListContainersParameters{ +// Prefix: name, +// Timeout: 90, +// }) +// if err != nil { +// return fmt.Errorf("Failed to retrieve storage containers in account %q: %s", name, err) +// } +// +// var found bool +// for _, cont := range containers.Containers { +// if cont.Name == name { +// found = true +// +// props := make(map[string]interface{}) +// props["last_modified"] = cont.Properties.LastModified +// props["lease_status"] = cont.Properties.LeaseStatus +// props["lease_state"] = cont.Properties.LeaseState +// props["lease_duration"] = cont.Properties.LeaseDuration +// +// d.Set("properties", props) +// } +// } +// +// if !found { +// log.Printf("[INFO] Storage container %q does not exist in account %q, removing from state...", name, storageAccountName) +// d.SetId("") +// } +// +// return nil +//} +// +//func resourceArmStorageContainerExists(d *schema.ResourceData, meta interface{}) (bool, error) { +// armClient := meta.(*ArmClient) +// +// resourceGroupName := d.Get("resource_group_name").(string) +// storageAccountName := d.Get("storage_account_name").(string) +// +// blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroupName, storageAccountName) +// if err != nil { +// return false, err +// } +// if !accountExists { +// log.Printf("[DEBUG] Storage account %q not found, removing container %q from state", storageAccountName, d.Id()) +// d.SetId("") +// return false, nil +// } +// +// name := d.Get("name").(string) +// +// log.Printf("[INFO] Checking existence of storage container %q in storage account %q", name, storageAccountName) +// exists, err := blobClient.ContainerExists(name) +// if err != nil { +// return false, fmt.Errorf("Error querying existence of storage container %q in storage account %q: %s", name, storageAccountName, err) +// } +// +// if !exists { +// log.Printf("[INFO] Storage container %q does not exist in account %q, removing from state...", name, storageAccountName) +// d.SetId("") +// } +// +// return exists, nil +//} +// +//// resourceAzureStorageContainerDelete does all the necessary API calls to +//// delete a storage container off Azure. +//func resourceArmStorageContainerDelete(d *schema.ResourceData, meta interface{}) error { +// armClient := meta.(*ArmClient) +// +// resourceGroupName := d.Get("resource_group_name").(string) +// storageAccountName := d.Get("storage_account_name").(string) +// +// blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroupName, storageAccountName) +// if err != nil { +// return err +// } +// if !accountExists { +// log.Printf("[INFO]Storage Account %q doesn't exist so the container won't exist", storageAccountName) +// return nil +// } +// +// name := d.Get("name").(string) +// +// log.Printf("[INFO] Deleting storage container %q in account %q", name, storageAccountName) +// if _, err := blobClient.DeleteContainerIfExists(name); err != nil { +// return fmt.Errorf("Error deleting storage container %q from storage account %q: %s", name, storageAccountName, err) +// } +// +// d.SetId("") +// return nil +//} diff --git a/builtin/providers/azurerm/resource_arm_storage_container_test.go b/builtin/providers/azurerm/resource_arm_storage_container_test.go index 68dcdd60c630..17e29a258cf5 100644 --- a/builtin/providers/azurerm/resource_arm_storage_container_test.go +++ b/builtin/providers/azurerm/resource_arm_storage_container_test.go @@ -1,241 +1,241 @@ package azurerm -import ( - "fmt" - "log" - "strings" - "testing" - - "github.com/Azure/azure-sdk-for-go/storage" - "github.com/hashicorp/terraform/helper/acctest" - "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/terraform" -) - -func TestAccAzureRMStorageContainer_basic(t *testing.T) { - var c storage.Container - - ri := acctest.RandInt() - rs := strings.ToLower(acctest.RandString(11)) - config := fmt.Sprintf(testAccAzureRMStorageContainer_basic, ri, rs) - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMStorageContainerDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: config, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMStorageContainerExists("azurerm_storage_container.test", &c), - ), - }, - }, - }) -} - -func TestAccAzureRMStorageContainer_disappears(t *testing.T) { - var c storage.Container - - ri := acctest.RandInt() - rs := strings.ToLower(acctest.RandString(11)) - config := fmt.Sprintf(testAccAzureRMStorageContainer_basic, ri, rs) - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMStorageContainerDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: config, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMStorageContainerExists("azurerm_storage_container.test", &c), - testAccARMStorageContainerDisappears("azurerm_storage_container.test", &c), - ), - ExpectNonEmptyPlan: true, - }, - }, - }) -} - -func testCheckAzureRMStorageContainerExists(name string, c *storage.Container) resource.TestCheckFunc { - return func(s *terraform.State) error { - - rs, ok := s.RootModule().Resources[name] - if !ok { - return fmt.Errorf("Not found: %s", name) - } - - name := rs.Primary.Attributes["name"] - storageAccountName := rs.Primary.Attributes["storage_account_name"] - resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] - if !hasResourceGroup { - return fmt.Errorf("Bad: no resource group found in state for storage container: %s", name) - } - - armClient := testAccProvider.Meta().(*ArmClient) - blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroup, storageAccountName) - if err != nil { - return err - } - if !accountExists { - return fmt.Errorf("Bad: Storage Account %q does not exist", storageAccountName) - } - - containers, err := blobClient.ListContainers(storage.ListContainersParameters{ - Prefix: name, - Timeout: 90, - }) - - if len(containers.Containers) == 0 { - return fmt.Errorf("Bad: Storage Container %q (storage account: %q) does not exist", name, storageAccountName) - } - - var found bool - for _, container := range containers.Containers { - if container.Name == name { - found = true - *c = container - } - } - - if !found { - return fmt.Errorf("Bad: Storage Container %q (storage account: %q) does not exist", name, storageAccountName) - } - - return nil - } -} - -func testAccARMStorageContainerDisappears(name string, c *storage.Container) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[name] - if !ok { - return fmt.Errorf("Not found: %s", name) - } - - armClient := testAccProvider.Meta().(*ArmClient) - - storageAccountName := rs.Primary.Attributes["storage_account_name"] - resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] - if !hasResourceGroup { - return fmt.Errorf("Bad: no resource group found in state for storage container: %s", c.Name) - } - - blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroup, storageAccountName) - if err != nil { - return err - } - if !accountExists { - log.Printf("[INFO]Storage Account %q doesn't exist so the container won't exist", storageAccountName) - return nil - } - - _, err = blobClient.DeleteContainerIfExists(c.Name) - if err != nil { - return err - } - - return nil - } -} - -func testCheckAzureRMStorageContainerDestroy(s *terraform.State) error { - for _, rs := range s.RootModule().Resources { - if rs.Type != "azurerm_storage_container" { - continue - } - - name := rs.Primary.Attributes["name"] - storageAccountName := rs.Primary.Attributes["storage_account_name"] - resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] - if !hasResourceGroup { - return fmt.Errorf("Bad: no resource group found in state for storage container: %s", name) - } - - armClient := testAccProvider.Meta().(*ArmClient) - blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroup, storageAccountName) - if err != nil { - //If we can't get keys then the blob can't exist - return nil - } - if !accountExists { - return nil - } - - containers, err := blobClient.ListContainers(storage.ListContainersParameters{ - Prefix: name, - Timeout: 90, - }) - - if err != nil { - return nil - } - - var found bool - for _, container := range containers.Containers { - if container.Name == name { - found = true - } - } - - if found { - return fmt.Errorf("Bad: Storage Container %q (storage account: %q) still exist", name, storageAccountName) - } - } - - return nil -} - -func TestValidateArmStorageContainerName(t *testing.T) { - validNames := []string{ - "valid-name", - "valid02-name", - } - for _, v := range validNames { - _, errors := validateArmStorageContainerName(v, "name") - if len(errors) != 0 { - t.Fatalf("%q should be a valid Storage Container Name: %q", v, errors) - } - } - - invalidNames := []string{ - "InvalidName1", - "-invalidname1", - "invalid_name", - "invalid!", - "ww", - strings.Repeat("w", 65), - } - for _, v := range invalidNames { - _, errors := validateArmStorageContainerName(v, "name") - if len(errors) == 0 { - t.Fatalf("%q should be an invalid Storage Container Name", v) - } - } -} - -var testAccAzureRMStorageContainer_basic = ` -resource "azurerm_resource_group" "test" { - name = "acctestrg-%d" - location = "westus" -} - -resource "azurerm_storage_account" "test" { - name = "acctestacc%s" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "westus" - account_type = "Standard_LRS" - - tags { - environment = "staging" - } -} - -resource "azurerm_storage_container" "test" { - name = "vhds" - resource_group_name = "${azurerm_resource_group.test.name}" - storage_account_name = "${azurerm_storage_account.test.name}" - container_access_type = "private" -} -` +//import ( +// "fmt" +// "log" +// "strings" +// "testing" +// +// "github.com/Azure/azure-sdk-for-go/storage" +// "github.com/hashicorp/terraform/helper/acctest" +// "github.com/hashicorp/terraform/helper/resource" +// "github.com/hashicorp/terraform/terraform" +//) +// +//func TestAccAzureRMStorageContainer_basic(t *testing.T) { +// var c storage.Container +// +// ri := acctest.RandInt() +// rs := strings.ToLower(acctest.RandString(11)) +// config := fmt.Sprintf(testAccAzureRMStorageContainer_basic, ri, rs) +// +// resource.Test(t, resource.TestCase{ +// PreCheck: func() { testAccPreCheck(t) }, +// Providers: testAccProviders, +// CheckDestroy: testCheckAzureRMStorageContainerDestroy, +// Steps: []resource.TestStep{ +// resource.TestStep{ +// Config: config, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMStorageContainerExists("azurerm_storage_container.test", &c), +// ), +// }, +// }, +// }) +//} +// +//func TestAccAzureRMStorageContainer_disappears(t *testing.T) { +// var c storage.Container +// +// ri := acctest.RandInt() +// rs := strings.ToLower(acctest.RandString(11)) +// config := fmt.Sprintf(testAccAzureRMStorageContainer_basic, ri, rs) +// +// resource.Test(t, resource.TestCase{ +// PreCheck: func() { testAccPreCheck(t) }, +// Providers: testAccProviders, +// CheckDestroy: testCheckAzureRMStorageContainerDestroy, +// Steps: []resource.TestStep{ +// resource.TestStep{ +// Config: config, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMStorageContainerExists("azurerm_storage_container.test", &c), +// testAccARMStorageContainerDisappears("azurerm_storage_container.test", &c), +// ), +// ExpectNonEmptyPlan: true, +// }, +// }, +// }) +//} +// +//func testCheckAzureRMStorageContainerExists(name string, c *storage.Container) resource.TestCheckFunc { +// return func(s *terraform.State) error { +// +// rs, ok := s.RootModule().Resources[name] +// if !ok { +// return fmt.Errorf("Not found: %s", name) +// } +// +// name := rs.Primary.Attributes["name"] +// storageAccountName := rs.Primary.Attributes["storage_account_name"] +// resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] +// if !hasResourceGroup { +// return fmt.Errorf("Bad: no resource group found in state for storage container: %s", name) +// } +// +// armClient := testAccProvider.Meta().(*ArmClient) +// blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroup, storageAccountName) +// if err != nil { +// return err +// } +// if !accountExists { +// return fmt.Errorf("Bad: Storage Account %q does not exist", storageAccountName) +// } +// +// containers, err := blobClient.ListContainers(storage.ListContainersParameters{ +// Prefix: name, +// Timeout: 90, +// }) +// +// if len(containers.Containers) == 0 { +// return fmt.Errorf("Bad: Storage Container %q (storage account: %q) does not exist", name, storageAccountName) +// } +// +// var found bool +// for _, container := range containers.Containers { +// if container.Name == name { +// found = true +// *c = container +// } +// } +// +// if !found { +// return fmt.Errorf("Bad: Storage Container %q (storage account: %q) does not exist", name, storageAccountName) +// } +// +// return nil +// } +//} +// +//func testAccARMStorageContainerDisappears(name string, c *storage.Container) resource.TestCheckFunc { +// return func(s *terraform.State) error { +// rs, ok := s.RootModule().Resources[name] +// if !ok { +// return fmt.Errorf("Not found: %s", name) +// } +// +// armClient := testAccProvider.Meta().(*ArmClient) +// +// storageAccountName := rs.Primary.Attributes["storage_account_name"] +// resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] +// if !hasResourceGroup { +// return fmt.Errorf("Bad: no resource group found in state for storage container: %s", c.Name) +// } +// +// blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroup, storageAccountName) +// if err != nil { +// return err +// } +// if !accountExists { +// log.Printf("[INFO]Storage Account %q doesn't exist so the container won't exist", storageAccountName) +// return nil +// } +// +// _, err = blobClient.DeleteContainerIfExists(c.Name) +// if err != nil { +// return err +// } +// +// return nil +// } +//} +// +//func testCheckAzureRMStorageContainerDestroy(s *terraform.State) error { +// for _, rs := range s.RootModule().Resources { +// if rs.Type != "azurerm_storage_container" { +// continue +// } +// +// name := rs.Primary.Attributes["name"] +// storageAccountName := rs.Primary.Attributes["storage_account_name"] +// resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] +// if !hasResourceGroup { +// return fmt.Errorf("Bad: no resource group found in state for storage container: %s", name) +// } +// +// armClient := testAccProvider.Meta().(*ArmClient) +// blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroup, storageAccountName) +// if err != nil { +// //If we can't get keys then the blob can't exist +// return nil +// } +// if !accountExists { +// return nil +// } +// +// containers, err := blobClient.ListContainers(storage.ListContainersParameters{ +// Prefix: name, +// Timeout: 90, +// }) +// +// if err != nil { +// return nil +// } +// +// var found bool +// for _, container := range containers.Containers { +// if container.Name == name { +// found = true +// } +// } +// +// if found { +// return fmt.Errorf("Bad: Storage Container %q (storage account: %q) still exist", name, storageAccountName) +// } +// } +// +// return nil +//} +// +//func TestValidateArmStorageContainerName(t *testing.T) { +// validNames := []string{ +// "valid-name", +// "valid02-name", +// } +// for _, v := range validNames { +// _, errors := validateArmStorageContainerName(v, "name") +// if len(errors) != 0 { +// t.Fatalf("%q should be a valid Storage Container Name: %q", v, errors) +// } +// } +// +// invalidNames := []string{ +// "InvalidName1", +// "-invalidname1", +// "invalid_name", +// "invalid!", +// "ww", +// strings.Repeat("w", 65), +// } +// for _, v := range invalidNames { +// _, errors := validateArmStorageContainerName(v, "name") +// if len(errors) == 0 { +// t.Fatalf("%q should be an invalid Storage Container Name", v) +// } +// } +//} +// +//var testAccAzureRMStorageContainer_basic = ` +//resource "azurerm_resource_group" "test" { +// name = "acctestrg-%d" +// location = "westus" +//} +// +//resource "azurerm_storage_account" "test" { +// name = "acctestacc%s" +// resource_group_name = "${azurerm_resource_group.test.name}" +// location = "westus" +// account_type = "Standard_LRS" +// +// tags { +// environment = "staging" +// } +//} +// +//resource "azurerm_storage_container" "test" { +// name = "vhds" +// resource_group_name = "${azurerm_resource_group.test.name}" +// storage_account_name = "${azurerm_storage_account.test.name}" +// container_access_type = "private" +//} +//` diff --git a/builtin/providers/azurerm/resource_arm_storage_queue.go b/builtin/providers/azurerm/resource_arm_storage_queue.go index f1bd4e644dd0..c4515186eead 100644 --- a/builtin/providers/azurerm/resource_arm_storage_queue.go +++ b/builtin/providers/azurerm/resource_arm_storage_queue.go @@ -16,13 +16,13 @@ func resourceArmStorageQueue() *schema.Resource { Delete: resourceArmStorageQueueDelete, Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ + "name": { Type: schema.TypeString, Required: true, ForceNew: true, ValidateFunc: validateArmStorageQueueName, }, - "resource_group_name": &schema.Schema{ + "resource_group_name": { Type: schema.TypeString, Required: true, ForceNew: true, diff --git a/builtin/providers/azurerm/resource_arm_subnet.go b/builtin/providers/azurerm/resource_arm_subnet.go index 58acbc6ccb9d..701fdf0fef69 100644 --- a/builtin/providers/azurerm/resource_arm_subnet.go +++ b/builtin/providers/azurerm/resource_arm_subnet.go @@ -1,188 +1,188 @@ package azurerm -import ( - "fmt" - "log" - "net/http" - "time" - - "github.com/Azure/azure-sdk-for-go/arm/network" - "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/helper/schema" -) - -func resourceArmSubnet() *schema.Resource { - return &schema.Resource{ - Create: resourceArmSubnetCreate, - Read: resourceArmSubnetRead, - Update: resourceArmSubnetCreate, - Delete: resourceArmSubnetDelete, - - Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - - "resource_group_name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - - "virtual_network_name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - - "address_prefix": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - - "network_security_group_id": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Computed: true, - }, - - "route_table_id": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Computed: true, - }, - - "ip_configurations": &schema.Schema{ - Type: schema.TypeSet, - Optional: true, - Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - }, - } -} - -func resourceArmSubnetCreate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient) - subnetClient := client.subnetClient - - log.Printf("[INFO] preparing arguments for Azure ARM Subnet creation.") - - name := d.Get("name").(string) - vnetName := d.Get("virtual_network_name").(string) - resGroup := d.Get("resource_group_name").(string) - addressPrefix := d.Get("address_prefix").(string) - - armMutexKV.Lock(vnetName) - defer armMutexKV.Unlock(vnetName) - - properties := network.SubnetPropertiesFormat{ - AddressPrefix: &addressPrefix, - } - - if v, ok := d.GetOk("network_security_group_id"); ok { - nsgId := v.(string) - properties.NetworkSecurityGroup = &network.SecurityGroup{ - ID: &nsgId, - } - } - - if v, ok := d.GetOk("route_table_id"); ok { - rtId := v.(string) - properties.RouteTable = &network.RouteTable{ - ID: &rtId, - } - } - - subnet := network.Subnet{ - Name: &name, - Properties: &properties, - } - - resp, err := subnetClient.CreateOrUpdate(resGroup, vnetName, name, subnet) - if err != nil { - return err - } - - d.SetId(*resp.ID) - - log.Printf("[DEBUG] Waiting for Subnet (%s) to become available", name) - stateConf := &resource.StateChangeConf{ - Pending: []string{"Accepted", "Updating"}, - Target: []string{"Succeeded"}, - Refresh: subnetRuleStateRefreshFunc(client, resGroup, vnetName, name), - Timeout: 10 * time.Minute, - } - if _, err := stateConf.WaitForState(); err != nil { - return fmt.Errorf("Error waiting for Subnet (%s) to become available: %s", name, err) - } - - return resourceArmSubnetRead(d, meta) -} - -func resourceArmSubnetRead(d *schema.ResourceData, meta interface{}) error { - subnetClient := meta.(*ArmClient).subnetClient - - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - resGroup := id.ResourceGroup - vnetName := id.Path["virtualNetworks"] - name := id.Path["subnets"] - - resp, err := subnetClient.Get(resGroup, vnetName, name, "") - if resp.StatusCode == http.StatusNotFound { - d.SetId("") - return nil - } - if err != nil { - return fmt.Errorf("Error making Read request on Azure Subnet %s: %s", name, err) - } - - if resp.Properties.IPConfigurations != nil && len(*resp.Properties.IPConfigurations) > 0 { - ips := make([]string, 0, len(*resp.Properties.IPConfigurations)) - for _, ip := range *resp.Properties.IPConfigurations { - ips = append(ips, *ip.ID) - } - - if err := d.Set("ip_configurations", ips); err != nil { - return err - } - } - - return nil -} - -func resourceArmSubnetDelete(d *schema.ResourceData, meta interface{}) error { - subnetClient := meta.(*ArmClient).subnetClient - - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - resGroup := id.ResourceGroup - name := id.Path["subnets"] - vnetName := id.Path["virtualNetworks"] - - armMutexKV.Lock(vnetName) - defer armMutexKV.Unlock(vnetName) - - _, err = subnetClient.Delete(resGroup, vnetName, name) - - return err -} - -func subnetRuleStateRefreshFunc(client *ArmClient, resourceGroupName string, virtualNetworkName string, subnetName string) resource.StateRefreshFunc { - return func() (interface{}, string, error) { - res, err := client.subnetClient.Get(resourceGroupName, virtualNetworkName, subnetName, "") - if err != nil { - return nil, "", fmt.Errorf("Error issuing read request in subnetRuleStateRefreshFunc to Azure ARM for subnet '%s' (RG: '%s') (VNN: '%s'): %s", subnetName, resourceGroupName, virtualNetworkName, err) - } - - return res, *res.Properties.ProvisioningState, nil - } -} +//import ( +// "fmt" +// "log" +// "net/http" +// "time" +// +// "github.com/Azure/azure-sdk-for-go/arm/network" +// "github.com/hashicorp/terraform/helper/resource" +// "github.com/hashicorp/terraform/helper/schema" +//) +// +//func resourceArmSubnet() *schema.Resource { +// return &schema.Resource{ +// Create: resourceArmSubnetCreate, +// Read: resourceArmSubnetRead, +// Update: resourceArmSubnetCreate, +// Delete: resourceArmSubnetDelete, +// +// Schema: map[string]*schema.Schema{ +// "name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// }, +// +// "resource_group_name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// }, +// +// "virtual_network_name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// }, +// +// "address_prefix": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "network_security_group_id": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// Computed: true, +// }, +// +// "route_table_id": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// Computed: true, +// }, +// +// "ip_configurations": &schema.Schema{ +// Type: schema.TypeSet, +// Optional: true, +// Computed: true, +// Elem: &schema.Schema{Type: schema.TypeString}, +// Set: schema.HashString, +// }, +// }, +// } +//} +// +//func resourceArmSubnetCreate(d *schema.ResourceData, meta interface{}) error { +// client := meta.(*ArmClient) +// subnetClient := client.subnetClient +// +// log.Printf("[INFO] preparing arguments for Azure ARM Subnet creation.") +// +// name := d.Get("name").(string) +// vnetName := d.Get("virtual_network_name").(string) +// resGroup := d.Get("resource_group_name").(string) +// addressPrefix := d.Get("address_prefix").(string) +// +// armMutexKV.Lock(vnetName) +// defer armMutexKV.Unlock(vnetName) +// +// properties := network.SubnetPropertiesFormat{ +// AddressPrefix: &addressPrefix, +// } +// +// if v, ok := d.GetOk("network_security_group_id"); ok { +// nsgId := v.(string) +// properties.NetworkSecurityGroup = &network.SecurityGroup{ +// ID: &nsgId, +// } +// } +// +// if v, ok := d.GetOk("route_table_id"); ok { +// rtId := v.(string) +// properties.RouteTable = &network.RouteTable{ +// ID: &rtId, +// } +// } +// +// subnet := network.Subnet{ +// Name: &name, +// Properties: &properties, +// } +// +// resp, err := subnetClient.CreateOrUpdate(resGroup, vnetName, name, subnet) +// if err != nil { +// return err +// } +// +// d.SetId(*resp.ID) +// +// log.Printf("[DEBUG] Waiting for Subnet (%s) to become available", name) +// stateConf := &resource.StateChangeConf{ +// Pending: []string{"Accepted", "Updating"}, +// Target: []string{"Succeeded"}, +// Refresh: subnetRuleStateRefreshFunc(client, resGroup, vnetName, name), +// Timeout: 10 * time.Minute, +// } +// if _, err := stateConf.WaitForState(); err != nil { +// return fmt.Errorf("Error waiting for Subnet (%s) to become available: %s", name, err) +// } +// +// return resourceArmSubnetRead(d, meta) +//} +// +//func resourceArmSubnetRead(d *schema.ResourceData, meta interface{}) error { +// subnetClient := meta.(*ArmClient).subnetClient +// +// id, err := parseAzureResourceID(d.Id()) +// if err != nil { +// return err +// } +// resGroup := id.ResourceGroup +// vnetName := id.Path["virtualNetworks"] +// name := id.Path["subnets"] +// +// resp, err := subnetClient.Get(resGroup, vnetName, name, "") +// if resp.StatusCode == http.StatusNotFound { +// d.SetId("") +// return nil +// } +// if err != nil { +// return fmt.Errorf("Error making Read request on Azure Subnet %s: %s", name, err) +// } +// +// if resp.Properties.IPConfigurations != nil && len(*resp.Properties.IPConfigurations) > 0 { +// ips := make([]string, 0, len(*resp.Properties.IPConfigurations)) +// for _, ip := range *resp.Properties.IPConfigurations { +// ips = append(ips, *ip.ID) +// } +// +// if err := d.Set("ip_configurations", ips); err != nil { +// return err +// } +// } +// +// return nil +//} +// +//func resourceArmSubnetDelete(d *schema.ResourceData, meta interface{}) error { +// subnetClient := meta.(*ArmClient).subnetClient +// +// id, err := parseAzureResourceID(d.Id()) +// if err != nil { +// return err +// } +// resGroup := id.ResourceGroup +// name := id.Path["subnets"] +// vnetName := id.Path["virtualNetworks"] +// +// armMutexKV.Lock(vnetName) +// defer armMutexKV.Unlock(vnetName) +// +// _, err = subnetClient.Delete(resGroup, vnetName, name) +// +// return err +//} +// +//func subnetRuleStateRefreshFunc(client *ArmClient, resourceGroupName string, virtualNetworkName string, subnetName string) resource.StateRefreshFunc { +// return func() (interface{}, string, error) { +// res, err := client.subnetClient.Get(resourceGroupName, virtualNetworkName, subnetName, "") +// if err != nil { +// return nil, "", fmt.Errorf("Error issuing read request in subnetRuleStateRefreshFunc to Azure ARM for subnet '%s' (RG: '%s') (VNN: '%s'): %s", subnetName, resourceGroupName, virtualNetworkName, err) +// } +// +// return res, *res.Properties.ProvisioningState, nil +// } +//} diff --git a/builtin/providers/azurerm/resource_arm_subnet_test.go b/builtin/providers/azurerm/resource_arm_subnet_test.go index 844e04f99254..5f6314d26078 100644 --- a/builtin/providers/azurerm/resource_arm_subnet_test.go +++ b/builtin/providers/azurerm/resource_arm_subnet_test.go @@ -1,108 +1,108 @@ 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 TestAccAzureRMSubnet_basic(t *testing.T) { - - ri := acctest.RandInt() - config := fmt.Sprintf(testAccAzureRMSubnet_basic, ri, ri, ri) - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMSubnetDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: config, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMSubnetExists("azurerm_subnet.test"), - ), - }, - }, - }) -} - -func testCheckAzureRMSubnetExists(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) - } - - name := rs.Primary.Attributes["name"] - vnetName := rs.Primary.Attributes["virtual_network_name"] - resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] - if !hasResourceGroup { - return fmt.Errorf("Bad: no resource group found in state for subnet: %s", name) - } - - conn := testAccProvider.Meta().(*ArmClient).subnetClient - - resp, err := conn.Get(resourceGroup, vnetName, name, "") - if err != nil { - return fmt.Errorf("Bad: Get on subnetClient: %s", err) - } - - if resp.StatusCode == http.StatusNotFound { - return fmt.Errorf("Bad: Subnet %q (resource group: %q) does not exist", name, resourceGroup) - } - - return nil - } -} - -func testCheckAzureRMSubnetDestroy(s *terraform.State) error { - conn := testAccProvider.Meta().(*ArmClient).subnetClient - - for _, rs := range s.RootModule().Resources { - if rs.Type != "azurerm_subnet" { - continue - } - - name := rs.Primary.Attributes["name"] - vnetName := rs.Primary.Attributes["virtual_network_name"] - resourceGroup := rs.Primary.Attributes["resource_group_name"] - - resp, err := conn.Get(resourceGroup, vnetName, name, "") - - if err != nil { - return nil - } - - if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("Subnet still exists:\n%#v", resp.Properties) - } - } - - return nil -} - -var testAccAzureRMSubnet_basic = ` -resource "azurerm_resource_group" "test" { - name = "acctestrg-%d" - location = "West US" -} - -resource "azurerm_virtual_network" "test" { - name = "acctestvirtnet%d" - address_space = ["10.0.0.0/16"] - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" -} - -resource "azurerm_subnet" "test" { - name = "acctestsubnet%d" - resource_group_name = "${azurerm_resource_group.test.name}" - virtual_network_name = "${azurerm_virtual_network.test.name}" - address_prefix = "10.0.2.0/24" -} -` +//import ( +// "fmt" +// "net/http" +// "testing" +// +// "github.com/hashicorp/terraform/helper/acctest" +// "github.com/hashicorp/terraform/helper/resource" +// "github.com/hashicorp/terraform/terraform" +//) +// +//func TestAccAzureRMSubnet_basic(t *testing.T) { +// +// ri := acctest.RandInt() +// config := fmt.Sprintf(testAccAzureRMSubnet_basic, ri, ri, ri) +// +// resource.Test(t, resource.TestCase{ +// PreCheck: func() { testAccPreCheck(t) }, +// Providers: testAccProviders, +// CheckDestroy: testCheckAzureRMSubnetDestroy, +// Steps: []resource.TestStep{ +// resource.TestStep{ +// Config: config, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMSubnetExists("azurerm_subnet.test"), +// ), +// }, +// }, +// }) +//} +// +//func testCheckAzureRMSubnetExists(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) +// } +// +// name := rs.Primary.Attributes["name"] +// vnetName := rs.Primary.Attributes["virtual_network_name"] +// resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] +// if !hasResourceGroup { +// return fmt.Errorf("Bad: no resource group found in state for subnet: %s", name) +// } +// +// conn := testAccProvider.Meta().(*ArmClient).subnetClient +// +// resp, err := conn.Get(resourceGroup, vnetName, name, "") +// if err != nil { +// return fmt.Errorf("Bad: Get on subnetClient: %s", err) +// } +// +// if resp.StatusCode == http.StatusNotFound { +// return fmt.Errorf("Bad: Subnet %q (resource group: %q) does not exist", name, resourceGroup) +// } +// +// return nil +// } +//} +// +//func testCheckAzureRMSubnetDestroy(s *terraform.State) error { +// conn := testAccProvider.Meta().(*ArmClient).subnetClient +// +// for _, rs := range s.RootModule().Resources { +// if rs.Type != "azurerm_subnet" { +// continue +// } +// +// name := rs.Primary.Attributes["name"] +// vnetName := rs.Primary.Attributes["virtual_network_name"] +// resourceGroup := rs.Primary.Attributes["resource_group_name"] +// +// resp, err := conn.Get(resourceGroup, vnetName, name, "") +// +// if err != nil { +// return nil +// } +// +// if resp.StatusCode != http.StatusNotFound { +// return fmt.Errorf("Subnet still exists:\n%#v", resp.Properties) +// } +// } +// +// return nil +//} +// +//var testAccAzureRMSubnet_basic = ` +//resource "azurerm_resource_group" "test" { +// name = "acctestrg-%d" +// location = "West US" +//} +// +//resource "azurerm_virtual_network" "test" { +// name = "acctestvirtnet%d" +// address_space = ["10.0.0.0/16"] +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +//} +// +//resource "azurerm_subnet" "test" { +// name = "acctestsubnet%d" +// resource_group_name = "${azurerm_resource_group.test.name}" +// virtual_network_name = "${azurerm_virtual_network.test.name}" +// address_prefix = "10.0.2.0/24" +//} +//` diff --git a/builtin/providers/azurerm/resource_arm_template_deployment.go b/builtin/providers/azurerm/resource_arm_template_deployment.go index 33b8b0f8f320..d7dabf34ba6a 100644 --- a/builtin/providers/azurerm/resource_arm_template_deployment.go +++ b/builtin/providers/azurerm/resource_arm_template_deployment.go @@ -1,213 +1,213 @@ package azurerm -import ( - "encoding/json" - "fmt" - "log" - "net/http" - "strings" - "time" - - "github.com/Azure/azure-sdk-for-go/arm/resources/resources" - "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/helper/schema" -) - -func resourceArmTemplateDeployment() *schema.Resource { - return &schema.Resource{ - Create: resourceArmTemplateDeploymentCreate, - Read: resourceArmTemplateDeploymentRead, - Update: resourceArmTemplateDeploymentCreate, - Delete: resourceArmTemplateDeploymentDelete, - - Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - - "resource_group_name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - - "template_body": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Computed: true, - StateFunc: normalizeJson, - }, - - "parameters": &schema.Schema{ - Type: schema.TypeMap, - Optional: true, - }, - - "outputs": &schema.Schema{ - Type: schema.TypeMap, - Computed: true, - }, - - "deployment_mode": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - }, - } -} - -func resourceArmTemplateDeploymentCreate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient) - deployClient := client.deploymentsClient - - name := d.Get("name").(string) - resGroup := d.Get("resource_group_name").(string) - deploymentMode := d.Get("deployment_mode").(string) - - log.Printf("[INFO] preparing arguments for Azure ARM Template Deployment creation.") - properties := resources.DeploymentProperties{ - Mode: resources.DeploymentMode(deploymentMode), - } - - if v, ok := d.GetOk("parameters"); ok { - params := v.(map[string]interface{}) - - newParams := make(map[string]interface{}, len(params)) - for key, val := range params { - newParams[key] = struct { - Value interface{} - }{ - Value: val, - } - } - - properties.Parameters = &newParams - } - - if v, ok := d.GetOk("template_body"); ok { - template, err := expandTemplateBody(v.(string)) - if err != nil { - return err - } - - properties.Template = &template - } - - deployment := resources.Deployment{ - Properties: &properties, - } - resp, err := deployClient.CreateOrUpdate(resGroup, name, deployment) - if err != nil { - return nil - } - - d.SetId(*resp.ID) - - log.Printf("[DEBUG] Waiting for Template Deployment (%s) to become available", name) - stateConf := &resource.StateChangeConf{ - Pending: []string{"creating", "updating", "accepted", "running"}, - Target: []string{"succeeded"}, - Refresh: templateDeploymentStateRefreshFunc(client, resGroup, name), - Timeout: 40 * time.Minute, - } - if _, err := stateConf.WaitForState(); err != nil { - return fmt.Errorf("Error waiting for Template Deployment (%s) to become available: %s", name, err) - } - - return resourceArmTemplateDeploymentRead(d, meta) -} - -func resourceArmTemplateDeploymentRead(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient) - deployClient := client.deploymentsClient - - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - resGroup := id.ResourceGroup - name := id.Path["deployments"] - if name == "" { - name = id.Path["Deployments"] - } - - resp, err := deployClient.Get(resGroup, name) - if resp.StatusCode == http.StatusNotFound { - d.SetId("") - return nil - } - if err != nil { - return fmt.Errorf("Error making Read request on Azure RM Template Deployment %s: %s", name, err) - } - var outputs map[string]string - if resp.Properties.Outputs != nil && len(*resp.Properties.Outputs) > 0 { - outputs = make(map[string]string) - for key, output := range *resp.Properties.Outputs { - outputMap := output.(map[string]interface{}) - outputValue, ok := outputMap["value"] - if !ok { - // No value - continue - } - - outputs[key] = outputValue.(string) - } - } - - d.Set("outputs", outputs) - - return nil -} - -func resourceArmTemplateDeploymentDelete(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient) - deployClient := client.deploymentsClient - - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - resGroup := id.ResourceGroup - name := id.Path["deployments"] - if name == "" { - name = id.Path["Deployments"] - } - - _, err = deployClient.Delete(resGroup, name) - return nil -} - -func expandTemplateBody(template string) (map[string]interface{}, error) { - var templateBody map[string]interface{} - err := json.Unmarshal([]byte(template), &templateBody) - if err != nil { - return nil, fmt.Errorf("Error Expanding the template_body for Azure RM Template Deployment") - } - return templateBody, nil -} - -func normalizeJson(jsonString interface{}) string { - if jsonString == nil || jsonString == "" { - return "" - } - var j interface{} - err := json.Unmarshal([]byte(jsonString.(string)), &j) - if err != nil { - return fmt.Sprintf("Error parsing JSON: %s", err) - } - b, _ := json.Marshal(j) - return string(b[:]) -} - -func templateDeploymentStateRefreshFunc(client *ArmClient, resourceGroupName string, name string) resource.StateRefreshFunc { - return func() (interface{}, string, error) { - res, err := client.deploymentsClient.Get(resourceGroupName, name) - if err != nil { - return nil, "", fmt.Errorf("Error issuing read request in templateDeploymentStateRefreshFunc to Azure ARM for Template Deployment '%s' (RG: '%s'): %s", name, resourceGroupName, err) - } - - return res, strings.ToLower(*res.Properties.ProvisioningState), nil - } -} +//import ( +// "encoding/json" +// "fmt" +// "log" +// "net/http" +// "strings" +// "time" +// +// "github.com/Azure/azure-sdk-for-go/arm/resources/resources" +// "github.com/hashicorp/terraform/helper/resource" +// "github.com/hashicorp/terraform/helper/schema" +//) +// +//func resourceArmTemplateDeployment() *schema.Resource { +// return &schema.Resource{ +// Create: resourceArmTemplateDeploymentCreate, +// Read: resourceArmTemplateDeploymentRead, +// Update: resourceArmTemplateDeploymentCreate, +// Delete: resourceArmTemplateDeploymentDelete, +// +// Schema: map[string]*schema.Schema{ +// "name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// }, +// +// "resource_group_name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// }, +// +// "template_body": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// Computed: true, +// StateFunc: normalizeJson, +// }, +// +// "parameters": &schema.Schema{ +// Type: schema.TypeMap, +// Optional: true, +// }, +// +// "outputs": &schema.Schema{ +// Type: schema.TypeMap, +// Computed: true, +// }, +// +// "deployment_mode": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// }, +// } +//} +// +//func resourceArmTemplateDeploymentCreate(d *schema.ResourceData, meta interface{}) error { +// client := meta.(*ArmClient) +// deployClient := client.deploymentsClient +// +// name := d.Get("name").(string) +// resGroup := d.Get("resource_group_name").(string) +// deploymentMode := d.Get("deployment_mode").(string) +// +// log.Printf("[INFO] preparing arguments for Azure ARM Template Deployment creation.") +// properties := resources.DeploymentProperties{ +// Mode: resources.DeploymentMode(deploymentMode), +// } +// +// if v, ok := d.GetOk("parameters"); ok { +// params := v.(map[string]interface{}) +// +// newParams := make(map[string]interface{}, len(params)) +// for key, val := range params { +// newParams[key] = struct { +// Value interface{} +// }{ +// Value: val, +// } +// } +// +// properties.Parameters = &newParams +// } +// +// if v, ok := d.GetOk("template_body"); ok { +// template, err := expandTemplateBody(v.(string)) +// if err != nil { +// return err +// } +// +// properties.Template = &template +// } +// +// deployment := resources.Deployment{ +// Properties: &properties, +// } +// resp, err := deployClient.CreateOrUpdate(resGroup, name, deployment) +// if err != nil { +// return nil +// } +// +// d.SetId(*resp.ID) +// +// log.Printf("[DEBUG] Waiting for Template Deployment (%s) to become available", name) +// stateConf := &resource.StateChangeConf{ +// Pending: []string{"creating", "updating", "accepted", "running"}, +// Target: []string{"succeeded"}, +// Refresh: templateDeploymentStateRefreshFunc(client, resGroup, name), +// Timeout: 40 * time.Minute, +// } +// if _, err := stateConf.WaitForState(); err != nil { +// return fmt.Errorf("Error waiting for Template Deployment (%s) to become available: %s", name, err) +// } +// +// return resourceArmTemplateDeploymentRead(d, meta) +//} +// +//func resourceArmTemplateDeploymentRead(d *schema.ResourceData, meta interface{}) error { +// client := meta.(*ArmClient) +// deployClient := client.deploymentsClient +// +// id, err := parseAzureResourceID(d.Id()) +// if err != nil { +// return err +// } +// resGroup := id.ResourceGroup +// name := id.Path["deployments"] +// if name == "" { +// name = id.Path["Deployments"] +// } +// +// resp, err := deployClient.Get(resGroup, name) +// if resp.StatusCode == http.StatusNotFound { +// d.SetId("") +// return nil +// } +// if err != nil { +// return fmt.Errorf("Error making Read request on Azure RM Template Deployment %s: %s", name, err) +// } +// var outputs map[string]string +// if resp.Properties.Outputs != nil && len(*resp.Properties.Outputs) > 0 { +// outputs = make(map[string]string) +// for key, output := range *resp.Properties.Outputs { +// outputMap := output.(map[string]interface{}) +// outputValue, ok := outputMap["value"] +// if !ok { +// // No value +// continue +// } +// +// outputs[key] = outputValue.(string) +// } +// } +// +// d.Set("outputs", outputs) +// +// return nil +//} +// +//func resourceArmTemplateDeploymentDelete(d *schema.ResourceData, meta interface{}) error { +// client := meta.(*ArmClient) +// deployClient := client.deploymentsClient +// +// id, err := parseAzureResourceID(d.Id()) +// if err != nil { +// return err +// } +// resGroup := id.ResourceGroup +// name := id.Path["deployments"] +// if name == "" { +// name = id.Path["Deployments"] +// } +// +// _, err = deployClient.Delete(resGroup, name) +// return nil +//} +// +//func expandTemplateBody(template string) (map[string]interface{}, error) { +// var templateBody map[string]interface{} +// err := json.Unmarshal([]byte(template), &templateBody) +// if err != nil { +// return nil, fmt.Errorf("Error Expanding the template_body for Azure RM Template Deployment") +// } +// return templateBody, nil +//} +// +//func normalizeJson(jsonString interface{}) string { +// if jsonString == nil || jsonString == "" { +// return "" +// } +// var j interface{} +// err := json.Unmarshal([]byte(jsonString.(string)), &j) +// if err != nil { +// return fmt.Sprintf("Error parsing JSON: %s", err) +// } +// b, _ := json.Marshal(j) +// return string(b[:]) +//} +// +//func templateDeploymentStateRefreshFunc(client *ArmClient, resourceGroupName string, name string) resource.StateRefreshFunc { +// return func() (interface{}, string, error) { +// res, err := client.deploymentsClient.Get(resourceGroupName, name) +// if err != nil { +// return nil, "", fmt.Errorf("Error issuing read request in templateDeploymentStateRefreshFunc to Azure ARM for Template Deployment '%s' (RG: '%s'): %s", name, resourceGroupName, err) +// } +// +// return res, strings.ToLower(*res.Properties.ProvisioningState), nil +// } +//} diff --git a/builtin/providers/azurerm/resource_arm_template_deployment_test.go b/builtin/providers/azurerm/resource_arm_template_deployment_test.go index 188f33da92c5..0a3707d6454b 100644 --- a/builtin/providers/azurerm/resource_arm_template_deployment_test.go +++ b/builtin/providers/azurerm/resource_arm_template_deployment_test.go @@ -1,251 +1,251 @@ 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 TestAccAzureRMTemplateDeployment_basic(t *testing.T) { - ri := acctest.RandInt() - config := fmt.Sprintf(testAccAzureRMTemplateDeployment_basicExample, ri, ri) - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMTemplateDeploymentDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: config, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMTemplateDeploymentExists("azurerm_template_deployment.test"), - ), - }, - }, - }) -} - -func TestAccAzureRMTemplateDeployment_withParams(t *testing.T) { - ri := acctest.RandInt() - config := fmt.Sprintf(testAccAzureRMTemplateDeployment_withParams, ri, ri, ri) - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMTemplateDeploymentDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: config, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMTemplateDeploymentExists("azurerm_template_deployment.test"), - resource.TestCheckResourceAttr("azurerm_template_deployment.test", "outputs.testOutput", "Output Value"), - ), - }, - }, - }) -} - -func testCheckAzureRMTemplateDeploymentExists(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) - } - - name := rs.Primary.Attributes["name"] - resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] - if !hasResourceGroup { - return fmt.Errorf("Bad: no resource group found in state for template deployment: %s", name) - } - - conn := testAccProvider.Meta().(*ArmClient).deploymentsClient - - resp, err := conn.Get(resourceGroup, name) - if err != nil { - return fmt.Errorf("Bad: Get on deploymentsClient: %s", err) - } - - if resp.StatusCode == http.StatusNotFound { - return fmt.Errorf("Bad: TemplateDeployment %q (resource group: %q) does not exist", name, resourceGroup) - } - - return nil - } -} - -func testCheckAzureRMTemplateDeploymentDestroy(s *terraform.State) error { - conn := testAccProvider.Meta().(*ArmClient).vmClient - - for _, rs := range s.RootModule().Resources { - if rs.Type != "azurerm_template_deployment" { - continue - } - - name := rs.Primary.Attributes["name"] - resourceGroup := rs.Primary.Attributes["resource_group_name"] - - resp, err := conn.Get(resourceGroup, name, "") - - if err != nil { - return nil - } - - if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("Template Deployment still exists:\n%#v", resp.Properties) - } - } - - return nil -} - -var testAccAzureRMTemplateDeployment_basicExample = ` - resource "azurerm_resource_group" "test" { - name = "acctestrg-%d" - location = "West US" - } - - resource "azurerm_template_deployment" "test" { - name = "acctesttemplate-%d" - resource_group_name = "${azurerm_resource_group.test.name}" - template_body = < 1023 { - errors = append(errors, fmt.Errorf( - "The `disk_size_gb` can only be between 1 and 1023")) - } - return - }, - }, - - "lun": &schema.Schema{ - Type: schema.TypeInt, - Required: true, - }, - }, - }, - }, - - "os_profile": &schema.Schema{ - Type: schema.TypeSet, - Required: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "computer_name": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Computed: true, - }, - - "admin_username": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - - "admin_password": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - - "custom_data": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Computed: true, - }, - }, - }, - Set: resourceArmVirtualMachineStorageOsProfileHash, - }, - - "os_profile_windows_config": &schema.Schema{ - Type: schema.TypeSet, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "provision_vm_agent": &schema.Schema{ - Type: schema.TypeBool, - Optional: true, - }, - "enable_automatic_upgrades": &schema.Schema{ - Type: schema.TypeBool, - Optional: true, - }, - "winrm": &schema.Schema{ - Type: schema.TypeSet, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "protocol": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - "certificate_url": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - }, - }, - }, - }, - "additional_unattend_config": &schema.Schema{ - Type: schema.TypeSet, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "pass": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - "component": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - "setting_name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - "content": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - }, - }, - }, - }, - }, - Set: resourceArmVirtualMachineStorageOsProfileWindowsConfigHash, - }, - - "os_profile_linux_config": &schema.Schema{ - Type: schema.TypeSet, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "disable_password_authentication": &schema.Schema{ - Type: schema.TypeBool, - Required: true, - }, - "ssh_keys": &schema.Schema{ - Type: schema.TypeList, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "path": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - "key_data": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - }, - }, - }, - }, - }, - }, - Set: resourceArmVirtualMachineStorageOsProfileLinuxConfigHash, - }, - - "os_profile_secrets": &schema.Schema{ - Type: schema.TypeSet, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "source_vault_id": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - - "vault_certificates": &schema.Schema{ - Type: schema.TypeSet, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "certificate_url": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - "certificate_store": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - }, - }, - }, - }, - }, - }, - }, - - "network_interface_ids": &schema.Schema{ - Type: schema.TypeSet, - Required: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - }, - - "tags": tagsSchema(), - }, - } -} - -func resourceArmVirtualMachineCreate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient) - vmClient := client.vmClient - - log.Printf("[INFO] preparing arguments for Azure ARM Virtual Machine creation.") - - name := d.Get("name").(string) - location := d.Get("location").(string) - resGroup := d.Get("resource_group_name").(string) - tags := d.Get("tags").(map[string]interface{}) - expandedTags := expandTags(tags) - - osDisk, err := expandAzureRmVirtualMachineOsDisk(d) - if err != nil { - return err - } - storageProfile := compute.StorageProfile{ - OsDisk: osDisk, - } - - if _, ok := d.GetOk("storage_image_reference"); ok { - imageRef, err := expandAzureRmVirtualMachineImageReference(d) - if err != nil { - return err - } - storageProfile.ImageReference = imageRef - } - - if _, ok := d.GetOk("storage_data_disk"); ok { - dataDisks, err := expandAzureRmVirtualMachineDataDisk(d) - if err != nil { - return err - } - storageProfile.DataDisks = &dataDisks - } - - networkProfile := expandAzureRmVirtualMachineNetworkProfile(d) - vmSize := d.Get("vm_size").(string) - properties := compute.VirtualMachineProperties{ - NetworkProfile: &networkProfile, - HardwareProfile: &compute.HardwareProfile{ - VMSize: compute.VirtualMachineSizeTypes(vmSize), - }, - StorageProfile: &storageProfile, - } - - osProfile, err := expandAzureRmVirtualMachineOsProfile(d) - if err != nil { - return err - } - properties.OsProfile = osProfile - - if v, ok := d.GetOk("availability_set_id"); ok { - availabilitySet := v.(string) - availSet := compute.SubResource{ - ID: &availabilitySet, - } - - properties.AvailabilitySet = &availSet - } - - vm := compute.VirtualMachine{ - Name: &name, - Location: &location, - Properties: &properties, - Tags: expandedTags, - } - - if _, ok := d.GetOk("plan"); ok { - plan, err := expandAzureRmVirtualMachinePlan(d) - if err != nil { - return err - } - - vm.Plan = plan - } - - resp, vmErr := vmClient.CreateOrUpdate(resGroup, name, vm) - if vmErr != nil { - return vmErr - } - - d.SetId(*resp.ID) - - log.Printf("[DEBUG] Waiting for Virtual Machine (%s) to become available", name) - stateConf := &resource.StateChangeConf{ - Pending: []string{"Creating", "Updating"}, - Target: []string{"Succeeded"}, - Refresh: virtualMachineStateRefreshFunc(client, resGroup, name), - Timeout: 20 * time.Minute, - MinTimeout: 10 * time.Second, - } - if _, err := stateConf.WaitForState(); err != nil { - return fmt.Errorf("Error waiting for Virtual Machine (%s) to become available: %s", name, err) - } - - return resourceArmVirtualMachineRead(d, meta) -} - -func resourceArmVirtualMachineRead(d *schema.ResourceData, meta interface{}) error { - vmClient := meta.(*ArmClient).vmClient - - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - resGroup := id.ResourceGroup - name := id.Path["virtualMachines"] - - resp, err := vmClient.Get(resGroup, name, "") - if resp.StatusCode == http.StatusNotFound { - d.SetId("") - return nil - } - if err != nil { - return fmt.Errorf("Error making Read request on Azure Virtual Machine %s: %s", name, err) - } - - if resp.Plan != nil { - if err := d.Set("plan", flattenAzureRmVirtualMachinePlan(resp.Plan)); err != nil { - return fmt.Errorf("[DEBUG] Error setting Virtual Machine Plan error: %#v", err) - } - } - - if resp.Properties.AvailabilitySet != nil { - d.Set("availability_set_id", strings.ToLower(*resp.Properties.AvailabilitySet.ID)) - } - - d.Set("vm_size", resp.Properties.HardwareProfile.VMSize) - - if resp.Properties.StorageProfile.ImageReference != nil { - if err := d.Set("storage_image_reference", schema.NewSet(resourceArmVirtualMachineStorageImageReferenceHash, flattenAzureRmVirtualMachineImageReference(resp.Properties.StorageProfile.ImageReference))); err != nil { - return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage Image Reference error: %#v", err) - } - } - - if err := d.Set("storage_os_disk", schema.NewSet(resourceArmVirtualMachineStorageOsDiskHash, flattenAzureRmVirtualMachineOsDisk(resp.Properties.StorageProfile.OsDisk))); err != nil { - return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage OS Disk error: %#v", err) - } - - if resp.Properties.StorageProfile.DataDisks != nil { - if err := d.Set("storage_data_disk", flattenAzureRmVirtualMachineDataDisk(resp.Properties.StorageProfile.DataDisks)); err != nil { - return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage Data Disks error: %#v", err) - } - } - - if err := d.Set("os_profile", schema.NewSet(resourceArmVirtualMachineStorageOsProfileHash, flattenAzureRmVirtualMachineOsProfile(resp.Properties.OsProfile))); err != nil { - return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage OS Profile: %#v", err) - } - - if resp.Properties.OsProfile.WindowsConfiguration != nil { - if err := d.Set("os_profile_windows_config", schema.NewSet(resourceArmVirtualMachineStorageOsProfileWindowsConfigHash, flattenAzureRmVirtualMachineOsProfileWindowsConfiguration(resp.Properties.OsProfile.WindowsConfiguration))); err != nil { - return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage OS Profile Windows Configuration: %#v", err) - } - } - - if resp.Properties.OsProfile.LinuxConfiguration != nil { - if err := d.Set("os_profile_linux_config", flattenAzureRmVirtualMachineOsProfileLinuxConfiguration(resp.Properties.OsProfile.LinuxConfiguration)); err != nil { - return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage OS Profile Linux Configuration: %#v", err) - } - } - - if resp.Properties.OsProfile.Secrets != nil { - if err := d.Set("os_profile_secrets", flattenAzureRmVirtualMachineOsProfileSecrets(resp.Properties.OsProfile.Secrets)); err != nil { - return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage OS Profile Secrets: %#v", err) - } - } - - if resp.Properties.NetworkProfile != nil { - if err := d.Set("network_interface_ids", flattenAzureRmVirtualMachineNetworkInterfaces(resp.Properties.NetworkProfile)); err != nil { - return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage Network Interfaces: %#v", err) - } - } - - flattenAndSetTags(d, resp.Tags) - - return nil -} - -func resourceArmVirtualMachineDelete(d *schema.ResourceData, meta interface{}) error { - vmClient := meta.(*ArmClient).vmClient - - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - resGroup := id.ResourceGroup - name := id.Path["virtualMachines"] - - _, err = vmClient.Delete(resGroup, name) - - return err -} - -func virtualMachineStateRefreshFunc(client *ArmClient, resourceGroupName string, vmName string) resource.StateRefreshFunc { - return func() (interface{}, string, error) { - res, err := client.vmClient.Get(resourceGroupName, vmName, "") - if err != nil { - return nil, "", fmt.Errorf("Error issuing read request in virtualMachineStateRefreshFunc to Azure ARM for Virtual Machine '%s' (RG: '%s'): %s", vmName, resourceGroupName, err) - } - - return res, *res.Properties.ProvisioningState, nil - } -} - -func resourceArmVirtualMachinePlanHash(v interface{}) int { - var buf bytes.Buffer - m := v.(map[string]interface{}) - buf.WriteString(fmt.Sprintf("%s-", m["name"].(string))) - buf.WriteString(fmt.Sprintf("%s-", m["publisher"].(string))) - buf.WriteString(fmt.Sprintf("%s-", m["product"].(string))) - - return hashcode.String(buf.String()) -} - -func resourceArmVirtualMachineStorageImageReferenceHash(v interface{}) int { - var buf bytes.Buffer - m := v.(map[string]interface{}) - buf.WriteString(fmt.Sprintf("%s-", m["publisher"].(string))) - buf.WriteString(fmt.Sprintf("%s-", m["offer"].(string))) - buf.WriteString(fmt.Sprintf("%s-", m["sku"].(string))) - - return hashcode.String(buf.String()) -} - -func resourceArmVirtualMachineStorageOsProfileHash(v interface{}) int { - var buf bytes.Buffer - m := v.(map[string]interface{}) - buf.WriteString(fmt.Sprintf("%s-", m["admin_username"].(string))) - buf.WriteString(fmt.Sprintf("%s-", m["computer_name"].(string))) - return hashcode.String(buf.String()) -} - -func resourceArmVirtualMachineStorageDataDiskHash(v interface{}) int { - var buf bytes.Buffer - m := v.(map[string]interface{}) - buf.WriteString(fmt.Sprintf("%s-", m["name"].(string))) - buf.WriteString(fmt.Sprintf("%s-", m["vhd_uri"].(string))) - buf.WriteString(fmt.Sprintf("%s-", m["create_option"].(string))) - buf.WriteString(fmt.Sprintf("%d-", m["disk_size_gb"].(int))) - buf.WriteString(fmt.Sprintf("%d-", m["lun"].(int))) - - return hashcode.String(buf.String()) -} - -func resourceArmVirtualMachineStorageOsDiskHash(v interface{}) int { - var buf bytes.Buffer - m := v.(map[string]interface{}) - buf.WriteString(fmt.Sprintf("%s-", m["name"].(string))) - buf.WriteString(fmt.Sprintf("%s-", m["vhd_uri"].(string))) - - return hashcode.String(buf.String()) -} - -func resourceArmVirtualMachineStorageOsProfileLinuxConfigHash(v interface{}) int { - var buf bytes.Buffer - m := v.(map[string]interface{}) - buf.WriteString(fmt.Sprintf("%t-", m["disable_password_authentication"].(bool))) - - return hashcode.String(buf.String()) -} - -func resourceArmVirtualMachineStorageOsProfileWindowsConfigHash(v interface{}) int { - var buf bytes.Buffer - m := v.(map[string]interface{}) - if m["provision_vm_agent"] != nil { - buf.WriteString(fmt.Sprintf("%t-", m["provision_vm_agent"].(bool))) - } - if m["enable_automatic_upgrades"] != nil { - buf.WriteString(fmt.Sprintf("%t-", m["enable_automatic_upgrades"].(bool))) - } - return hashcode.String(buf.String()) -} - -func flattenAzureRmVirtualMachinePlan(plan *compute.Plan) map[string]interface{} { - result := make(map[string]interface{}) - result["name"] = *plan.Name - result["publisher"] = *plan.Publisher - result["product"] = *plan.Product - - return result -} - -func flattenAzureRmVirtualMachineImageReference(image *compute.ImageReference) []interface{} { - result := make(map[string]interface{}) - result["offer"] = *image.Offer - result["publisher"] = *image.Publisher - result["sku"] = *image.Sku - - if image.Version != nil { - result["version"] = *image.Version - } - - return []interface{}{result} -} - -func flattenAzureRmVirtualMachineNetworkInterfaces(profile *compute.NetworkProfile) []string { - result := make([]string, 0, len(*profile.NetworkInterfaces)) - for _, nic := range *profile.NetworkInterfaces { - result = append(result, *nic.ID) - } - return result -} - -func flattenAzureRmVirtualMachineOsProfileSecrets(secrets *[]compute.VaultSecretGroup) []map[string]interface{} { - result := make([]map[string]interface{}, 0, len(*secrets)) - for _, secret := range *secrets { - s := map[string]interface{}{ - "source_vault_id": *secret.SourceVault.ID, - } - - if secret.VaultCertificates != nil { - certs := make([]map[string]interface{}, 0, len(*secret.VaultCertificates)) - for _, cert := range *secret.VaultCertificates { - vaultCert := make(map[string]interface{}) - vaultCert["certificate_url"] = *cert.CertificateURL - - if cert.CertificateStore != nil { - vaultCert["certificate_store"] = *cert.CertificateStore - } - - certs = append(certs, vaultCert) - } - - s["vault_certificates"] = certs - } - - result = append(result, s) - } - return result -} - -func flattenAzureRmVirtualMachineDataDisk(disks *[]compute.DataDisk) interface{} { - result := make([]interface{}, len(*disks)) - for i, disk := range *disks { - l := make(map[string]interface{}) - l["name"] = *disk.Name - l["vhd_uri"] = *disk.Vhd.URI - l["create_option"] = disk.CreateOption - l["disk_size_gb"] = *disk.DiskSizeGB - l["lun"] = *disk.Lun - - result[i] = l - } - return result -} - -func flattenAzureRmVirtualMachineOsProfile(osProfile *compute.OSProfile) []interface{} { - result := make(map[string]interface{}) - result["computer_name"] = *osProfile.ComputerName - result["admin_username"] = *osProfile.AdminUsername - if osProfile.CustomData != nil { - result["custom_data"] = *osProfile.CustomData - } - - return []interface{}{result} -} - -func flattenAzureRmVirtualMachineOsProfileWindowsConfiguration(config *compute.WindowsConfiguration) []interface{} { - result := make(map[string]interface{}) - - if config.ProvisionVMAgent != nil { - result["provision_vm_agent"] = *config.ProvisionVMAgent - } - - if config.EnableAutomaticUpdates != nil { - result["enable_automatic_upgrades"] = *config.EnableAutomaticUpdates - } - - if config.WinRM != nil { - listeners := make([]map[string]interface{}, 0, len(*config.WinRM.Listeners)) - for _, i := range *config.WinRM.Listeners { - listener := make(map[string]interface{}) - listener["protocol"] = i.Protocol - - if i.CertificateURL != nil { - listener["certificate_url"] = *i.CertificateURL - } - - listeners = append(listeners, listener) - } - - result["winrm"] = listeners - } - - if config.AdditionalUnattendContent != nil { - content := make([]map[string]interface{}, 0, len(*config.AdditionalUnattendContent)) - for _, i := range *config.AdditionalUnattendContent { - c := make(map[string]interface{}) - c["pass"] = i.PassName - c["component"] = i.ComponentName - c["setting_name"] = i.SettingName - c["content"] = *i.Content - - content = append(content, c) - } - - result["additional_unattend_config"] = content - } - - return []interface{}{result} -} - -func flattenAzureRmVirtualMachineOsProfileLinuxConfiguration(config *compute.LinuxConfiguration) []interface{} { - - result := make(map[string]interface{}) - result["disable_password_authentication"] = *config.DisablePasswordAuthentication - - if config.SSH != nil && len(*config.SSH.PublicKeys) > 0 { - ssh_keys := make([]map[string]interface{}, len(*config.SSH.PublicKeys)) - for _, i := range *config.SSH.PublicKeys { - key := make(map[string]interface{}) - key["path"] = *i.Path - - if i.KeyData != nil { - key["key_data"] = *i.KeyData - } - - ssh_keys = append(ssh_keys, key) - } - - result["ssh_keys"] = ssh_keys - } - - return []interface{}{result} -} - -func flattenAzureRmVirtualMachineOsDisk(disk *compute.OSDisk) []interface{} { - result := make(map[string]interface{}) - result["name"] = *disk.Name - result["vhd_uri"] = *disk.Vhd.URI - result["create_option"] = disk.CreateOption - result["caching"] = disk.Caching - - return []interface{}{result} -} - -func expandAzureRmVirtualMachinePlan(d *schema.ResourceData) (*compute.Plan, error) { - planConfigs := d.Get("plan").(*schema.Set).List() - - if len(planConfigs) != 1 { - return nil, fmt.Errorf("Cannot specify more than one plan.") - } - - planConfig := planConfigs[0].(map[string]interface{}) - - publisher := planConfig["publisher"].(string) - name := planConfig["name"].(string) - product := planConfig["product"].(string) - - return &compute.Plan{ - Publisher: &publisher, - Name: &name, - Product: &product, - }, nil -} - -func expandAzureRmVirtualMachineOsProfile(d *schema.ResourceData) (*compute.OSProfile, error) { - osProfiles := d.Get("os_profile").(*schema.Set).List() - - if len(osProfiles) != 1 { - return nil, fmt.Errorf("[ERROR] Only 1 OS Profile Can be specified for an Azure RM Virtual Machine") - } - - osProfile := osProfiles[0].(map[string]interface{}) - - adminUsername := osProfile["admin_username"].(string) - adminPassword := osProfile["admin_password"].(string) - - profile := &compute.OSProfile{ - AdminUsername: &adminUsername, - } - - if adminPassword != "" { - profile.AdminPassword = &adminPassword - } - - if _, ok := d.GetOk("os_profile_windows_config"); ok { - winConfig, err := expandAzureRmVirtualMachineOsProfileWindowsConfig(d) - if err != nil { - return nil, err - } - if winConfig != nil { - profile.WindowsConfiguration = winConfig - } - } - - if _, ok := d.GetOk("os_profile_linux_config"); ok { - linuxConfig, err := expandAzureRmVirtualMachineOsProfileLinuxConfig(d) - if err != nil { - return nil, err - } - if linuxConfig != nil { - profile.LinuxConfiguration = linuxConfig - } - } - - if _, ok := d.GetOk("os_profile_secrets"); ok { - secrets := expandAzureRmVirtualMachineOsProfileSecrets(d) - if secrets != nil { - profile.Secrets = secrets - } - } - - if v := osProfile["computer_name"].(string); v != "" { - profile.ComputerName = &v - } - if v := osProfile["custom_data"].(string); v != "" { - profile.CustomData = &v - } - - return profile, nil -} - -func expandAzureRmVirtualMachineOsProfileSecrets(d *schema.ResourceData) *[]compute.VaultSecretGroup { - secretsConfig := d.Get("os_profile_secrets").(*schema.Set).List() - secrets := make([]compute.VaultSecretGroup, 0, len(secretsConfig)) - - for _, secretConfig := range secretsConfig { - config := secretConfig.(map[string]interface{}) - sourceVaultId := config["source_vault_id"].(string) - - vaultSecretGroup := compute.VaultSecretGroup{ - SourceVault: &compute.SubResource{ - ID: &sourceVaultId, - }, - } - - if v := config["vault_certificates"]; v != nil { - certsConfig := v.(*schema.Set).List() - certs := make([]compute.VaultCertificate, 0, len(certsConfig)) - for _, certConfig := range certsConfig { - config := certConfig.(map[string]interface{}) - - certUrl := config["certificate_url"].(string) - cert := compute.VaultCertificate{ - CertificateURL: &certUrl, - } - if v := config["certificate_store"].(string); v != "" { - cert.CertificateStore = &v - } - - certs = append(certs, cert) - } - vaultSecretGroup.VaultCertificates = &certs - } - - secrets = append(secrets, vaultSecretGroup) - } - - return &secrets -} - -func expandAzureRmVirtualMachineOsProfileLinuxConfig(d *schema.ResourceData) (*compute.LinuxConfiguration, error) { - osProfilesLinuxConfig := d.Get("os_profile_linux_config").(*schema.Set).List() - - if len(osProfilesLinuxConfig) != 1 { - return nil, fmt.Errorf("[ERROR] Only 1 OS Profile Linux Config Can be specified for an Azure RM Virtual Machine") - } - - linuxConfig := osProfilesLinuxConfig[0].(map[string]interface{}) - disablePasswordAuth := linuxConfig["disable_password_authentication"].(bool) - - config := &compute.LinuxConfiguration{ - DisablePasswordAuthentication: &disablePasswordAuth, - } - - linuxKeys := linuxConfig["ssh_keys"].([]interface{}) - sshPublicKeys := []compute.SSHPublicKey{} - for _, key := range linuxKeys { - - sshKey, ok := key.(map[string]interface{}) - if !ok { - continue - } - path := sshKey["path"].(string) - keyData := sshKey["key_data"].(string) - - sshPublicKey := compute.SSHPublicKey{ - Path: &path, - KeyData: &keyData, - } - - sshPublicKeys = append(sshPublicKeys, sshPublicKey) - } - - config.SSH = &compute.SSHConfiguration{ - PublicKeys: &sshPublicKeys, - } - - return config, nil -} - -func expandAzureRmVirtualMachineOsProfileWindowsConfig(d *schema.ResourceData) (*compute.WindowsConfiguration, error) { - osProfilesWindowsConfig := d.Get("os_profile_windows_config").(*schema.Set).List() - - if len(osProfilesWindowsConfig) != 1 { - return nil, fmt.Errorf("[ERROR] Only 1 OS Profile Windows Config Can be specified for an Azure RM Virtual Machine") - } - - osProfileConfig := osProfilesWindowsConfig[0].(map[string]interface{}) - config := &compute.WindowsConfiguration{} - - if v := osProfileConfig["provision_vm_agent"]; v != nil { - provision := v.(bool) - config.ProvisionVMAgent = &provision - } - - if v := osProfileConfig["enable_automatic_upgrades"]; v != nil { - update := v.(bool) - config.EnableAutomaticUpdates = &update - } - - if v := osProfileConfig["winrm"]; v != nil { - winRm := v.(*schema.Set).List() - if len(winRm) > 0 { - winRmListners := make([]compute.WinRMListener, 0, len(winRm)) - for _, winRmConfig := range winRm { - config := winRmConfig.(map[string]interface{}) - - protocol := config["protocol"].(string) - winRmListner := compute.WinRMListener{ - Protocol: compute.ProtocolTypes(protocol), - } - if v := config["certificate_url"].(string); v != "" { - winRmListner.CertificateURL = &v - } - - winRmListners = append(winRmListners, winRmListner) - } - config.WinRM = &compute.WinRMConfiguration{ - Listeners: &winRmListners, - } - } - } - if v := osProfileConfig["additional_unattend_config"]; v != nil { - additionalConfig := v.(*schema.Set).List() - if len(additionalConfig) > 0 { - additionalConfigContent := make([]compute.AdditionalUnattendContent, 0, len(additionalConfig)) - for _, addConfig := range additionalConfig { - config := addConfig.(map[string]interface{}) - pass := config["pass"].(string) - component := config["component"].(string) - settingName := config["setting_name"].(string) - content := config["content"].(string) - - addContent := compute.AdditionalUnattendContent{ - PassName: compute.PassNames(pass), - ComponentName: compute.ComponentNames(component), - SettingName: compute.SettingNames(settingName), - Content: &content, - } - - additionalConfigContent = append(additionalConfigContent, addContent) - } - config.AdditionalUnattendContent = &additionalConfigContent - } - } - return config, nil -} - -func expandAzureRmVirtualMachineDataDisk(d *schema.ResourceData) ([]compute.DataDisk, error) { - disks := d.Get("storage_data_disk").([]interface{}) - data_disks := make([]compute.DataDisk, 0, len(disks)) - for _, disk_config := range disks { - config := disk_config.(map[string]interface{}) - - name := config["name"].(string) - vhd := config["vhd_uri"].(string) - createOption := config["create_option"].(string) - lun := config["lun"].(int) - disk_size := config["disk_size_gb"].(int) - - data_disk := compute.DataDisk{ - Name: &name, - Vhd: &compute.VirtualHardDisk{ - URI: &vhd, - }, - Lun: &lun, - DiskSizeGB: &disk_size, - CreateOption: compute.DiskCreateOptionTypes(createOption), - } - - data_disks = append(data_disks, data_disk) - } - - return data_disks, nil -} - -func expandAzureRmVirtualMachineImageReference(d *schema.ResourceData) (*compute.ImageReference, error) { - storageImageRefs := d.Get("storage_image_reference").(*schema.Set).List() - - if len(storageImageRefs) != 1 { - return nil, fmt.Errorf("Cannot specify more than one storage_image_reference.") - } - - storageImageRef := storageImageRefs[0].(map[string]interface{}) - - publisher := storageImageRef["publisher"].(string) - offer := storageImageRef["offer"].(string) - sku := storageImageRef["sku"].(string) - version := storageImageRef["version"].(string) - - return &compute.ImageReference{ - Publisher: &publisher, - Offer: &offer, - Sku: &sku, - Version: &version, - }, nil -} - -func expandAzureRmVirtualMachineNetworkProfile(d *schema.ResourceData) compute.NetworkProfile { - nicIds := d.Get("network_interface_ids").(*schema.Set).List() - network_interfaces := make([]compute.NetworkInterfaceReference, 0, len(nicIds)) - - network_profile := compute.NetworkProfile{} - - for _, nic := range nicIds { - id := nic.(string) - network_interface := compute.NetworkInterfaceReference{ - ID: &id, - } - network_interfaces = append(network_interfaces, network_interface) - } - - network_profile.NetworkInterfaces = &network_interfaces - - return network_profile -} - -func expandAzureRmVirtualMachineOsDisk(d *schema.ResourceData) (*compute.OSDisk, error) { - disks := d.Get("storage_os_disk").(*schema.Set).List() - - if len(disks) != 1 { - return nil, fmt.Errorf("[ERROR] Only 1 OS Disk Can be specified for an Azure RM Virtual Machine") - } - - disk := disks[0].(map[string]interface{}) - - name := disk["name"].(string) - vhdURI := disk["vhd_uri"].(string) - imageURI := disk["image_uri"].(string) - createOption := disk["create_option"].(string) - - osDisk := &compute.OSDisk{ - Name: &name, - Vhd: &compute.VirtualHardDisk{ - URI: &vhdURI, - }, - CreateOption: compute.DiskCreateOptionTypes(createOption), - } - - if v := disk["image_uri"].(string); v != "" { - osDisk.Image = &compute.VirtualHardDisk{ - URI: &imageURI, - } - } - - if v := disk["os_type"].(string); v != "" { - if v == "linux" { - osDisk.OsType = compute.Linux - } else if v == "windows" { - osDisk.OsType = compute.Windows - } else { - return nil, fmt.Errorf("[ERROR] os_type must be 'linux' or 'windows'") - } - } - - if v := disk["caching"].(string); v != "" { - osDisk.Caching = compute.CachingTypes(v) - } - - return osDisk, nil -} +//import ( +// "bytes" +// "fmt" +// "log" +// "net/http" +// "strings" +// "time" +// +// "github.com/Azure/azure-sdk-for-go/arm/compute" +// "github.com/hashicorp/terraform/helper/hashcode" +// "github.com/hashicorp/terraform/helper/resource" +// "github.com/hashicorp/terraform/helper/schema" +//) +// +//func resourceArmVirtualMachine() *schema.Resource { +// return &schema.Resource{ +// Create: resourceArmVirtualMachineCreate, +// Read: resourceArmVirtualMachineRead, +// Update: resourceArmVirtualMachineCreate, +// Delete: resourceArmVirtualMachineDelete, +// +// Schema: map[string]*schema.Schema{ +// "name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// }, +// +// "location": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// StateFunc: azureRMNormalizeLocation, +// }, +// +// "resource_group_name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// }, +// +// "plan": &schema.Schema{ +// Type: schema.TypeSet, +// Optional: true, +// Computed: true, +// Elem: &schema.Resource{ +// Schema: map[string]*schema.Schema{ +// "name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "publisher": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "product": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// }, +// }, +// Set: resourceArmVirtualMachinePlanHash, +// }, +// +// "availability_set_id": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// Computed: true, +// StateFunc: func(id interface{}) string { +// return strings.ToLower(id.(string)) +// }, +// }, +// +// "license_type": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// Computed: true, +// }, +// +// "vm_size": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "storage_image_reference": &schema.Schema{ +// Type: schema.TypeSet, +// Optional: true, +// Computed: true, +// Elem: &schema.Resource{ +// Schema: map[string]*schema.Schema{ +// "publisher": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "offer": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "sku": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "version": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// Computed: true, +// }, +// }, +// }, +// Set: resourceArmVirtualMachineStorageImageReferenceHash, +// }, +// +// "storage_os_disk": &schema.Schema{ +// Type: schema.TypeSet, +// Required: true, +// Elem: &schema.Resource{ +// Schema: map[string]*schema.Schema{ +// "os_type": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// }, +// +// "name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "vhd_uri": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "image_uri": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// }, +// +// "caching": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// Computed: true, +// }, +// +// "create_option": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// }, +// }, +// Set: resourceArmVirtualMachineStorageOsDiskHash, +// }, +// +// "storage_data_disk": &schema.Schema{ +// Type: schema.TypeList, +// Optional: true, +// Elem: &schema.Resource{ +// Schema: map[string]*schema.Schema{ +// "name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "vhd_uri": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "create_option": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "disk_size_gb": &schema.Schema{ +// Type: schema.TypeInt, +// Required: true, +// ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { +// value := v.(int) +// if value < 1 || value > 1023 { +// errors = append(errors, fmt.Errorf( +// "The `disk_size_gb` can only be between 1 and 1023")) +// } +// return +// }, +// }, +// +// "lun": &schema.Schema{ +// Type: schema.TypeInt, +// Required: true, +// }, +// }, +// }, +// }, +// +// "os_profile": &schema.Schema{ +// Type: schema.TypeSet, +// Required: true, +// Elem: &schema.Resource{ +// Schema: map[string]*schema.Schema{ +// "computer_name": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// Computed: true, +// }, +// +// "admin_username": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "admin_password": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "custom_data": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// Computed: true, +// }, +// }, +// }, +// Set: resourceArmVirtualMachineStorageOsProfileHash, +// }, +// +// "os_profile_windows_config": &schema.Schema{ +// Type: schema.TypeSet, +// Optional: true, +// Elem: &schema.Resource{ +// Schema: map[string]*schema.Schema{ +// "provision_vm_agent": &schema.Schema{ +// Type: schema.TypeBool, +// Optional: true, +// }, +// "enable_automatic_upgrades": &schema.Schema{ +// Type: schema.TypeBool, +// Optional: true, +// }, +// "winrm": &schema.Schema{ +// Type: schema.TypeSet, +// Optional: true, +// Elem: &schema.Resource{ +// Schema: map[string]*schema.Schema{ +// "protocol": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// "certificate_url": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// }, +// }, +// }, +// }, +// "additional_unattend_config": &schema.Schema{ +// Type: schema.TypeSet, +// Optional: true, +// Elem: &schema.Resource{ +// Schema: map[string]*schema.Schema{ +// "pass": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// "component": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// "setting_name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// "content": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// }, +// }, +// }, +// }, +// }, +// Set: resourceArmVirtualMachineStorageOsProfileWindowsConfigHash, +// }, +// +// "os_profile_linux_config": &schema.Schema{ +// Type: schema.TypeSet, +// Optional: true, +// Elem: &schema.Resource{ +// Schema: map[string]*schema.Schema{ +// "disable_password_authentication": &schema.Schema{ +// Type: schema.TypeBool, +// Required: true, +// }, +// "ssh_keys": &schema.Schema{ +// Type: schema.TypeList, +// Optional: true, +// Elem: &schema.Resource{ +// Schema: map[string]*schema.Schema{ +// "path": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// "key_data": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// }, +// }, +// }, +// }, +// }, +// }, +// Set: resourceArmVirtualMachineStorageOsProfileLinuxConfigHash, +// }, +// +// "os_profile_secrets": &schema.Schema{ +// Type: schema.TypeSet, +// Optional: true, +// Elem: &schema.Resource{ +// Schema: map[string]*schema.Schema{ +// "source_vault_id": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// +// "vault_certificates": &schema.Schema{ +// Type: schema.TypeSet, +// Optional: true, +// Elem: &schema.Resource{ +// Schema: map[string]*schema.Schema{ +// "certificate_url": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// "certificate_store": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// }, +// }, +// }, +// }, +// }, +// }, +// }, +// +// "network_interface_ids": &schema.Schema{ +// Type: schema.TypeSet, +// Required: true, +// Elem: &schema.Schema{Type: schema.TypeString}, +// Set: schema.HashString, +// }, +// +// "tags": tagsSchema(), +// }, +// } +//} +// +//func resourceArmVirtualMachineCreate(d *schema.ResourceData, meta interface{}) error { +// client := meta.(*ArmClient) +// vmClient := client.vmClient +// +// log.Printf("[INFO] preparing arguments for Azure ARM Virtual Machine creation.") +// +// name := d.Get("name").(string) +// location := d.Get("location").(string) +// resGroup := d.Get("resource_group_name").(string) +// tags := d.Get("tags").(map[string]interface{}) +// expandedTags := expandTags(tags) +// +// osDisk, err := expandAzureRmVirtualMachineOsDisk(d) +// if err != nil { +// return err +// } +// storageProfile := compute.StorageProfile{ +// OsDisk: osDisk, +// } +// +// if _, ok := d.GetOk("storage_image_reference"); ok { +// imageRef, err := expandAzureRmVirtualMachineImageReference(d) +// if err != nil { +// return err +// } +// storageProfile.ImageReference = imageRef +// } +// +// if _, ok := d.GetOk("storage_data_disk"); ok { +// dataDisks, err := expandAzureRmVirtualMachineDataDisk(d) +// if err != nil { +// return err +// } +// storageProfile.DataDisks = &dataDisks +// } +// +// networkProfile := expandAzureRmVirtualMachineNetworkProfile(d) +// vmSize := d.Get("vm_size").(string) +// properties := compute.VirtualMachineProperties{ +// NetworkProfile: &networkProfile, +// HardwareProfile: &compute.HardwareProfile{ +// VMSize: compute.VirtualMachineSizeTypes(vmSize), +// }, +// StorageProfile: &storageProfile, +// } +// +// osProfile, err := expandAzureRmVirtualMachineOsProfile(d) +// if err != nil { +// return err +// } +// properties.OsProfile = osProfile +// +// if v, ok := d.GetOk("availability_set_id"); ok { +// availabilitySet := v.(string) +// availSet := compute.SubResource{ +// ID: &availabilitySet, +// } +// +// properties.AvailabilitySet = &availSet +// } +// +// vm := compute.VirtualMachine{ +// Name: &name, +// Location: &location, +// Properties: &properties, +// Tags: expandedTags, +// } +// +// if _, ok := d.GetOk("plan"); ok { +// plan, err := expandAzureRmVirtualMachinePlan(d) +// if err != nil { +// return err +// } +// +// vm.Plan = plan +// } +// +// resp, vmErr := vmClient.CreateOrUpdate(resGroup, name, vm) +// if vmErr != nil { +// return vmErr +// } +// +// d.SetId(*resp.ID) +// +// log.Printf("[DEBUG] Waiting for Virtual Machine (%s) to become available", name) +// stateConf := &resource.StateChangeConf{ +// Pending: []string{"Creating", "Updating"}, +// Target: []string{"Succeeded"}, +// Refresh: virtualMachineStateRefreshFunc(client, resGroup, name), +// Timeout: 20 * time.Minute, +// MinTimeout: 10 * time.Second, +// } +// if _, err := stateConf.WaitForState(); err != nil { +// return fmt.Errorf("Error waiting for Virtual Machine (%s) to become available: %s", name, err) +// } +// +// return resourceArmVirtualMachineRead(d, meta) +//} +// +//func resourceArmVirtualMachineRead(d *schema.ResourceData, meta interface{}) error { +// vmClient := meta.(*ArmClient).vmClient +// +// id, err := parseAzureResourceID(d.Id()) +// if err != nil { +// return err +// } +// resGroup := id.ResourceGroup +// name := id.Path["virtualMachines"] +// +// resp, err := vmClient.Get(resGroup, name, "") +// if resp.StatusCode == http.StatusNotFound { +// d.SetId("") +// return nil +// } +// if err != nil { +// return fmt.Errorf("Error making Read request on Azure Virtual Machine %s: %s", name, err) +// } +// +// if resp.Plan != nil { +// if err := d.Set("plan", flattenAzureRmVirtualMachinePlan(resp.Plan)); err != nil { +// return fmt.Errorf("[DEBUG] Error setting Virtual Machine Plan error: %#v", err) +// } +// } +// +// if resp.Properties.AvailabilitySet != nil { +// d.Set("availability_set_id", strings.ToLower(*resp.Properties.AvailabilitySet.ID)) +// } +// +// d.Set("vm_size", resp.Properties.HardwareProfile.VMSize) +// +// if resp.Properties.StorageProfile.ImageReference != nil { +// if err := d.Set("storage_image_reference", schema.NewSet(resourceArmVirtualMachineStorageImageReferenceHash, flattenAzureRmVirtualMachineImageReference(resp.Properties.StorageProfile.ImageReference))); err != nil { +// return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage Image Reference error: %#v", err) +// } +// } +// +// if err := d.Set("storage_os_disk", schema.NewSet(resourceArmVirtualMachineStorageOsDiskHash, flattenAzureRmVirtualMachineOsDisk(resp.Properties.StorageProfile.OsDisk))); err != nil { +// return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage OS Disk error: %#v", err) +// } +// +// if resp.Properties.StorageProfile.DataDisks != nil { +// if err := d.Set("storage_data_disk", flattenAzureRmVirtualMachineDataDisk(resp.Properties.StorageProfile.DataDisks)); err != nil { +// return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage Data Disks error: %#v", err) +// } +// } +// +// if err := d.Set("os_profile", schema.NewSet(resourceArmVirtualMachineStorageOsProfileHash, flattenAzureRmVirtualMachineOsProfile(resp.Properties.OsProfile))); err != nil { +// return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage OS Profile: %#v", err) +// } +// +// if resp.Properties.OsProfile.WindowsConfiguration != nil { +// if err := d.Set("os_profile_windows_config", schema.NewSet(resourceArmVirtualMachineStorageOsProfileWindowsConfigHash, flattenAzureRmVirtualMachineOsProfileWindowsConfiguration(resp.Properties.OsProfile.WindowsConfiguration))); err != nil { +// return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage OS Profile Windows Configuration: %#v", err) +// } +// } +// +// if resp.Properties.OsProfile.LinuxConfiguration != nil { +// if err := d.Set("os_profile_linux_config", flattenAzureRmVirtualMachineOsProfileLinuxConfiguration(resp.Properties.OsProfile.LinuxConfiguration)); err != nil { +// return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage OS Profile Linux Configuration: %#v", err) +// } +// } +// +// if resp.Properties.OsProfile.Secrets != nil { +// if err := d.Set("os_profile_secrets", flattenAzureRmVirtualMachineOsProfileSecrets(resp.Properties.OsProfile.Secrets)); err != nil { +// return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage OS Profile Secrets: %#v", err) +// } +// } +// +// if resp.Properties.NetworkProfile != nil { +// if err := d.Set("network_interface_ids", flattenAzureRmVirtualMachineNetworkInterfaces(resp.Properties.NetworkProfile)); err != nil { +// return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage Network Interfaces: %#v", err) +// } +// } +// +// flattenAndSetTags(d, resp.Tags) +// +// return nil +//} +// +//func resourceArmVirtualMachineDelete(d *schema.ResourceData, meta interface{}) error { +// vmClient := meta.(*ArmClient).vmClient +// +// id, err := parseAzureResourceID(d.Id()) +// if err != nil { +// return err +// } +// resGroup := id.ResourceGroup +// name := id.Path["virtualMachines"] +// +// _, err = vmClient.Delete(resGroup, name) +// +// return err +//} +// +//func virtualMachineStateRefreshFunc(client *ArmClient, resourceGroupName string, vmName string) resource.StateRefreshFunc { +// return func() (interface{}, string, error) { +// res, err := client.vmClient.Get(resourceGroupName, vmName, "") +// if err != nil { +// return nil, "", fmt.Errorf("Error issuing read request in virtualMachineStateRefreshFunc to Azure ARM for Virtual Machine '%s' (RG: '%s'): %s", vmName, resourceGroupName, err) +// } +// +// return res, *res.Properties.ProvisioningState, nil +// } +//} +// +//func resourceArmVirtualMachinePlanHash(v interface{}) int { +// var buf bytes.Buffer +// m := v.(map[string]interface{}) +// buf.WriteString(fmt.Sprintf("%s-", m["name"].(string))) +// buf.WriteString(fmt.Sprintf("%s-", m["publisher"].(string))) +// buf.WriteString(fmt.Sprintf("%s-", m["product"].(string))) +// +// return hashcode.String(buf.String()) +//} +// +//func resourceArmVirtualMachineStorageImageReferenceHash(v interface{}) int { +// var buf bytes.Buffer +// m := v.(map[string]interface{}) +// buf.WriteString(fmt.Sprintf("%s-", m["publisher"].(string))) +// buf.WriteString(fmt.Sprintf("%s-", m["offer"].(string))) +// buf.WriteString(fmt.Sprintf("%s-", m["sku"].(string))) +// +// return hashcode.String(buf.String()) +//} +// +//func resourceArmVirtualMachineStorageOsProfileHash(v interface{}) int { +// var buf bytes.Buffer +// m := v.(map[string]interface{}) +// buf.WriteString(fmt.Sprintf("%s-", m["admin_username"].(string))) +// buf.WriteString(fmt.Sprintf("%s-", m["computer_name"].(string))) +// return hashcode.String(buf.String()) +//} +// +//func resourceArmVirtualMachineStorageDataDiskHash(v interface{}) int { +// var buf bytes.Buffer +// m := v.(map[string]interface{}) +// buf.WriteString(fmt.Sprintf("%s-", m["name"].(string))) +// buf.WriteString(fmt.Sprintf("%s-", m["vhd_uri"].(string))) +// buf.WriteString(fmt.Sprintf("%s-", m["create_option"].(string))) +// buf.WriteString(fmt.Sprintf("%d-", m["disk_size_gb"].(int))) +// buf.WriteString(fmt.Sprintf("%d-", m["lun"].(int))) +// +// return hashcode.String(buf.String()) +//} +// +//func resourceArmVirtualMachineStorageOsDiskHash(v interface{}) int { +// var buf bytes.Buffer +// m := v.(map[string]interface{}) +// buf.WriteString(fmt.Sprintf("%s-", m["name"].(string))) +// buf.WriteString(fmt.Sprintf("%s-", m["vhd_uri"].(string))) +// +// return hashcode.String(buf.String()) +//} +// +//func resourceArmVirtualMachineStorageOsProfileLinuxConfigHash(v interface{}) int { +// var buf bytes.Buffer +// m := v.(map[string]interface{}) +// buf.WriteString(fmt.Sprintf("%t-", m["disable_password_authentication"].(bool))) +// +// return hashcode.String(buf.String()) +//} +// +//func resourceArmVirtualMachineStorageOsProfileWindowsConfigHash(v interface{}) int { +// var buf bytes.Buffer +// m := v.(map[string]interface{}) +// if m["provision_vm_agent"] != nil { +// buf.WriteString(fmt.Sprintf("%t-", m["provision_vm_agent"].(bool))) +// } +// if m["enable_automatic_upgrades"] != nil { +// buf.WriteString(fmt.Sprintf("%t-", m["enable_automatic_upgrades"].(bool))) +// } +// return hashcode.String(buf.String()) +//} +// +//func flattenAzureRmVirtualMachinePlan(plan *compute.Plan) map[string]interface{} { +// result := make(map[string]interface{}) +// result["name"] = *plan.Name +// result["publisher"] = *plan.Publisher +// result["product"] = *plan.Product +// +// return result +//} +// +//func flattenAzureRmVirtualMachineImageReference(image *compute.ImageReference) []interface{} { +// result := make(map[string]interface{}) +// result["offer"] = *image.Offer +// result["publisher"] = *image.Publisher +// result["sku"] = *image.Sku +// +// if image.Version != nil { +// result["version"] = *image.Version +// } +// +// return []interface{}{result} +//} +// +//func flattenAzureRmVirtualMachineNetworkInterfaces(profile *compute.NetworkProfile) []string { +// result := make([]string, 0, len(*profile.NetworkInterfaces)) +// for _, nic := range *profile.NetworkInterfaces { +// result = append(result, *nic.ID) +// } +// return result +//} +// +//func flattenAzureRmVirtualMachineOsProfileSecrets(secrets *[]compute.VaultSecretGroup) []map[string]interface{} { +// result := make([]map[string]interface{}, 0, len(*secrets)) +// for _, secret := range *secrets { +// s := map[string]interface{}{ +// "source_vault_id": *secret.SourceVault.ID, +// } +// +// if secret.VaultCertificates != nil { +// certs := make([]map[string]interface{}, 0, len(*secret.VaultCertificates)) +// for _, cert := range *secret.VaultCertificates { +// vaultCert := make(map[string]interface{}) +// vaultCert["certificate_url"] = *cert.CertificateURL +// +// if cert.CertificateStore != nil { +// vaultCert["certificate_store"] = *cert.CertificateStore +// } +// +// certs = append(certs, vaultCert) +// } +// +// s["vault_certificates"] = certs +// } +// +// result = append(result, s) +// } +// return result +//} +// +//func flattenAzureRmVirtualMachineDataDisk(disks *[]compute.DataDisk) interface{} { +// result := make([]interface{}, len(*disks)) +// for i, disk := range *disks { +// l := make(map[string]interface{}) +// l["name"] = *disk.Name +// l["vhd_uri"] = *disk.Vhd.URI +// l["create_option"] = disk.CreateOption +// l["disk_size_gb"] = *disk.DiskSizeGB +// l["lun"] = *disk.Lun +// +// result[i] = l +// } +// return result +//} +// +//func flattenAzureRmVirtualMachineOsProfile(osProfile *compute.OSProfile) []interface{} { +// result := make(map[string]interface{}) +// result["computer_name"] = *osProfile.ComputerName +// result["admin_username"] = *osProfile.AdminUsername +// if osProfile.CustomData != nil { +// result["custom_data"] = *osProfile.CustomData +// } +// +// return []interface{}{result} +//} +// +//func flattenAzureRmVirtualMachineOsProfileWindowsConfiguration(config *compute.WindowsConfiguration) []interface{} { +// result := make(map[string]interface{}) +// +// if config.ProvisionVMAgent != nil { +// result["provision_vm_agent"] = *config.ProvisionVMAgent +// } +// +// if config.EnableAutomaticUpdates != nil { +// result["enable_automatic_upgrades"] = *config.EnableAutomaticUpdates +// } +// +// if config.WinRM != nil { +// listeners := make([]map[string]interface{}, 0, len(*config.WinRM.Listeners)) +// for _, i := range *config.WinRM.Listeners { +// listener := make(map[string]interface{}) +// listener["protocol"] = i.Protocol +// +// if i.CertificateURL != nil { +// listener["certificate_url"] = *i.CertificateURL +// } +// +// listeners = append(listeners, listener) +// } +// +// result["winrm"] = listeners +// } +// +// if config.AdditionalUnattendContent != nil { +// content := make([]map[string]interface{}, 0, len(*config.AdditionalUnattendContent)) +// for _, i := range *config.AdditionalUnattendContent { +// c := make(map[string]interface{}) +// c["pass"] = i.PassName +// c["component"] = i.ComponentName +// c["setting_name"] = i.SettingName +// c["content"] = *i.Content +// +// content = append(content, c) +// } +// +// result["additional_unattend_config"] = content +// } +// +// return []interface{}{result} +//} +// +//func flattenAzureRmVirtualMachineOsProfileLinuxConfiguration(config *compute.LinuxConfiguration) []interface{} { +// +// result := make(map[string]interface{}) +// result["disable_password_authentication"] = *config.DisablePasswordAuthentication +// +// if config.SSH != nil && len(*config.SSH.PublicKeys) > 0 { +// ssh_keys := make([]map[string]interface{}, len(*config.SSH.PublicKeys)) +// for _, i := range *config.SSH.PublicKeys { +// key := make(map[string]interface{}) +// key["path"] = *i.Path +// +// if i.KeyData != nil { +// key["key_data"] = *i.KeyData +// } +// +// ssh_keys = append(ssh_keys, key) +// } +// +// result["ssh_keys"] = ssh_keys +// } +// +// return []interface{}{result} +//} +// +//func flattenAzureRmVirtualMachineOsDisk(disk *compute.OSDisk) []interface{} { +// result := make(map[string]interface{}) +// result["name"] = *disk.Name +// result["vhd_uri"] = *disk.Vhd.URI +// result["create_option"] = disk.CreateOption +// result["caching"] = disk.Caching +// +// return []interface{}{result} +//} +// +//func expandAzureRmVirtualMachinePlan(d *schema.ResourceData) (*compute.Plan, error) { +// planConfigs := d.Get("plan").(*schema.Set).List() +// +// if len(planConfigs) != 1 { +// return nil, fmt.Errorf("Cannot specify more than one plan.") +// } +// +// planConfig := planConfigs[0].(map[string]interface{}) +// +// publisher := planConfig["publisher"].(string) +// name := planConfig["name"].(string) +// product := planConfig["product"].(string) +// +// return &compute.Plan{ +// Publisher: &publisher, +// Name: &name, +// Product: &product, +// }, nil +//} +// +//func expandAzureRmVirtualMachineOsProfile(d *schema.ResourceData) (*compute.OSProfile, error) { +// osProfiles := d.Get("os_profile").(*schema.Set).List() +// +// if len(osProfiles) != 1 { +// return nil, fmt.Errorf("[ERROR] Only 1 OS Profile Can be specified for an Azure RM Virtual Machine") +// } +// +// osProfile := osProfiles[0].(map[string]interface{}) +// +// adminUsername := osProfile["admin_username"].(string) +// adminPassword := osProfile["admin_password"].(string) +// +// profile := &compute.OSProfile{ +// AdminUsername: &adminUsername, +// } +// +// if adminPassword != "" { +// profile.AdminPassword = &adminPassword +// } +// +// if _, ok := d.GetOk("os_profile_windows_config"); ok { +// winConfig, err := expandAzureRmVirtualMachineOsProfileWindowsConfig(d) +// if err != nil { +// return nil, err +// } +// if winConfig != nil { +// profile.WindowsConfiguration = winConfig +// } +// } +// +// if _, ok := d.GetOk("os_profile_linux_config"); ok { +// linuxConfig, err := expandAzureRmVirtualMachineOsProfileLinuxConfig(d) +// if err != nil { +// return nil, err +// } +// if linuxConfig != nil { +// profile.LinuxConfiguration = linuxConfig +// } +// } +// +// if _, ok := d.GetOk("os_profile_secrets"); ok { +// secrets := expandAzureRmVirtualMachineOsProfileSecrets(d) +// if secrets != nil { +// profile.Secrets = secrets +// } +// } +// +// if v := osProfile["computer_name"].(string); v != "" { +// profile.ComputerName = &v +// } +// if v := osProfile["custom_data"].(string); v != "" { +// profile.CustomData = &v +// } +// +// return profile, nil +//} +// +//func expandAzureRmVirtualMachineOsProfileSecrets(d *schema.ResourceData) *[]compute.VaultSecretGroup { +// secretsConfig := d.Get("os_profile_secrets").(*schema.Set).List() +// secrets := make([]compute.VaultSecretGroup, 0, len(secretsConfig)) +// +// for _, secretConfig := range secretsConfig { +// config := secretConfig.(map[string]interface{}) +// sourceVaultId := config["source_vault_id"].(string) +// +// vaultSecretGroup := compute.VaultSecretGroup{ +// SourceVault: &compute.SubResource{ +// ID: &sourceVaultId, +// }, +// } +// +// if v := config["vault_certificates"]; v != nil { +// certsConfig := v.(*schema.Set).List() +// certs := make([]compute.VaultCertificate, 0, len(certsConfig)) +// for _, certConfig := range certsConfig { +// config := certConfig.(map[string]interface{}) +// +// certUrl := config["certificate_url"].(string) +// cert := compute.VaultCertificate{ +// CertificateURL: &certUrl, +// } +// if v := config["certificate_store"].(string); v != "" { +// cert.CertificateStore = &v +// } +// +// certs = append(certs, cert) +// } +// vaultSecretGroup.VaultCertificates = &certs +// } +// +// secrets = append(secrets, vaultSecretGroup) +// } +// +// return &secrets +//} +// +//func expandAzureRmVirtualMachineOsProfileLinuxConfig(d *schema.ResourceData) (*compute.LinuxConfiguration, error) { +// osProfilesLinuxConfig := d.Get("os_profile_linux_config").(*schema.Set).List() +// +// if len(osProfilesLinuxConfig) != 1 { +// return nil, fmt.Errorf("[ERROR] Only 1 OS Profile Linux Config Can be specified for an Azure RM Virtual Machine") +// } +// +// linuxConfig := osProfilesLinuxConfig[0].(map[string]interface{}) +// disablePasswordAuth := linuxConfig["disable_password_authentication"].(bool) +// +// config := &compute.LinuxConfiguration{ +// DisablePasswordAuthentication: &disablePasswordAuth, +// } +// +// linuxKeys := linuxConfig["ssh_keys"].([]interface{}) +// sshPublicKeys := []compute.SSHPublicKey{} +// for _, key := range linuxKeys { +// +// sshKey, ok := key.(map[string]interface{}) +// if !ok { +// continue +// } +// path := sshKey["path"].(string) +// keyData := sshKey["key_data"].(string) +// +// sshPublicKey := compute.SSHPublicKey{ +// Path: &path, +// KeyData: &keyData, +// } +// +// sshPublicKeys = append(sshPublicKeys, sshPublicKey) +// } +// +// config.SSH = &compute.SSHConfiguration{ +// PublicKeys: &sshPublicKeys, +// } +// +// return config, nil +//} +// +//func expandAzureRmVirtualMachineOsProfileWindowsConfig(d *schema.ResourceData) (*compute.WindowsConfiguration, error) { +// osProfilesWindowsConfig := d.Get("os_profile_windows_config").(*schema.Set).List() +// +// if len(osProfilesWindowsConfig) != 1 { +// return nil, fmt.Errorf("[ERROR] Only 1 OS Profile Windows Config Can be specified for an Azure RM Virtual Machine") +// } +// +// osProfileConfig := osProfilesWindowsConfig[0].(map[string]interface{}) +// config := &compute.WindowsConfiguration{} +// +// if v := osProfileConfig["provision_vm_agent"]; v != nil { +// provision := v.(bool) +// config.ProvisionVMAgent = &provision +// } +// +// if v := osProfileConfig["enable_automatic_upgrades"]; v != nil { +// update := v.(bool) +// config.EnableAutomaticUpdates = &update +// } +// +// if v := osProfileConfig["winrm"]; v != nil { +// winRm := v.(*schema.Set).List() +// if len(winRm) > 0 { +// winRmListners := make([]compute.WinRMListener, 0, len(winRm)) +// for _, winRmConfig := range winRm { +// config := winRmConfig.(map[string]interface{}) +// +// protocol := config["protocol"].(string) +// winRmListner := compute.WinRMListener{ +// Protocol: compute.ProtocolTypes(protocol), +// } +// if v := config["certificate_url"].(string); v != "" { +// winRmListner.CertificateURL = &v +// } +// +// winRmListners = append(winRmListners, winRmListner) +// } +// config.WinRM = &compute.WinRMConfiguration{ +// Listeners: &winRmListners, +// } +// } +// } +// if v := osProfileConfig["additional_unattend_config"]; v != nil { +// additionalConfig := v.(*schema.Set).List() +// if len(additionalConfig) > 0 { +// additionalConfigContent := make([]compute.AdditionalUnattendContent, 0, len(additionalConfig)) +// for _, addConfig := range additionalConfig { +// config := addConfig.(map[string]interface{}) +// pass := config["pass"].(string) +// component := config["component"].(string) +// settingName := config["setting_name"].(string) +// content := config["content"].(string) +// +// addContent := compute.AdditionalUnattendContent{ +// PassName: compute.PassNames(pass), +// ComponentName: compute.ComponentNames(component), +// SettingName: compute.SettingNames(settingName), +// Content: &content, +// } +// +// additionalConfigContent = append(additionalConfigContent, addContent) +// } +// config.AdditionalUnattendContent = &additionalConfigContent +// } +// } +// return config, nil +//} +// +//func expandAzureRmVirtualMachineDataDisk(d *schema.ResourceData) ([]compute.DataDisk, error) { +// disks := d.Get("storage_data_disk").([]interface{}) +// data_disks := make([]compute.DataDisk, 0, len(disks)) +// for _, disk_config := range disks { +// config := disk_config.(map[string]interface{}) +// +// name := config["name"].(string) +// vhd := config["vhd_uri"].(string) +// createOption := config["create_option"].(string) +// lun := config["lun"].(int) +// disk_size := config["disk_size_gb"].(int) +// +// data_disk := compute.DataDisk{ +// Name: &name, +// Vhd: &compute.VirtualHardDisk{ +// URI: &vhd, +// }, +// Lun: &lun, +// DiskSizeGB: &disk_size, +// CreateOption: compute.DiskCreateOptionTypes(createOption), +// } +// +// data_disks = append(data_disks, data_disk) +// } +// +// return data_disks, nil +//} +// +//func expandAzureRmVirtualMachineImageReference(d *schema.ResourceData) (*compute.ImageReference, error) { +// storageImageRefs := d.Get("storage_image_reference").(*schema.Set).List() +// +// if len(storageImageRefs) != 1 { +// return nil, fmt.Errorf("Cannot specify more than one storage_image_reference.") +// } +// +// storageImageRef := storageImageRefs[0].(map[string]interface{}) +// +// publisher := storageImageRef["publisher"].(string) +// offer := storageImageRef["offer"].(string) +// sku := storageImageRef["sku"].(string) +// version := storageImageRef["version"].(string) +// +// return &compute.ImageReference{ +// Publisher: &publisher, +// Offer: &offer, +// Sku: &sku, +// Version: &version, +// }, nil +//} +// +//func expandAzureRmVirtualMachineNetworkProfile(d *schema.ResourceData) compute.NetworkProfile { +// nicIds := d.Get("network_interface_ids").(*schema.Set).List() +// network_interfaces := make([]compute.NetworkInterfaceReference, 0, len(nicIds)) +// +// network_profile := compute.NetworkProfile{} +// +// for _, nic := range nicIds { +// id := nic.(string) +// network_interface := compute.NetworkInterfaceReference{ +// ID: &id, +// } +// network_interfaces = append(network_interfaces, network_interface) +// } +// +// network_profile.NetworkInterfaces = &network_interfaces +// +// return network_profile +//} +// +//func expandAzureRmVirtualMachineOsDisk(d *schema.ResourceData) (*compute.OSDisk, error) { +// disks := d.Get("storage_os_disk").(*schema.Set).List() +// +// if len(disks) != 1 { +// return nil, fmt.Errorf("[ERROR] Only 1 OS Disk Can be specified for an Azure RM Virtual Machine") +// } +// +// disk := disks[0].(map[string]interface{}) +// +// name := disk["name"].(string) +// vhdURI := disk["vhd_uri"].(string) +// imageURI := disk["image_uri"].(string) +// createOption := disk["create_option"].(string) +// +// osDisk := &compute.OSDisk{ +// Name: &name, +// Vhd: &compute.VirtualHardDisk{ +// URI: &vhdURI, +// }, +// CreateOption: compute.DiskCreateOptionTypes(createOption), +// } +// +// if v := disk["image_uri"].(string); v != "" { +// osDisk.Image = &compute.VirtualHardDisk{ +// URI: &imageURI, +// } +// } +// +// if v := disk["os_type"].(string); v != "" { +// if v == "linux" { +// osDisk.OsType = compute.Linux +// } else if v == "windows" { +// osDisk.OsType = compute.Windows +// } else { +// return nil, fmt.Errorf("[ERROR] os_type must be 'linux' or 'windows'") +// } +// } +// +// if v := disk["caching"].(string); v != "" { +// osDisk.Caching = compute.CachingTypes(v) +// } +// +// return osDisk, nil +//} diff --git a/builtin/providers/azurerm/resource_arm_virtual_machine_test.go b/builtin/providers/azurerm/resource_arm_virtual_machine_test.go index 8e11e9fa2088..099de061df0f 100644 --- a/builtin/providers/azurerm/resource_arm_virtual_machine_test.go +++ b/builtin/providers/azurerm/resource_arm_virtual_machine_test.go @@ -1,510 +1,510 @@ 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 TestAccAzureRMVirtualMachine_basicLinuxMachine(t *testing.T) { - ri := acctest.RandInt() - config := fmt.Sprintf(testAccAzureRMVirtualMachine_basicLinuxMachine, ri, ri, ri, ri, ri, ri, ri) - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMVirtualMachineDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: config, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test"), - ), - }, - }, - }) -} - -func TestAccAzureRMVirtualMachine_tags(t *testing.T) { - ri := acctest.RandInt() - preConfig := fmt.Sprintf(testAccAzureRMVirtualMachine_basicLinuxMachine, ri, ri, ri, ri, ri, ri, ri) - postConfig := fmt.Sprintf(testAccAzureRMVirtualMachine_basicLinuxMachineUpdated, ri, ri, ri, ri, ri, ri, ri) - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMVirtualMachineDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: preConfig, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test"), - resource.TestCheckResourceAttr( - "azurerm_virtual_machine.test", "tags.#", "2"), - resource.TestCheckResourceAttr( - "azurerm_virtual_machine.test", "tags.environment", "Production"), - resource.TestCheckResourceAttr( - "azurerm_virtual_machine.test", "tags.cost-center", "Ops"), - ), - }, - - resource.TestStep{ - Config: postConfig, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test"), - resource.TestCheckResourceAttr( - "azurerm_virtual_machine.test", "tags.#", "1"), - resource.TestCheckResourceAttr( - "azurerm_virtual_machine.test", "tags.environment", "Production"), - ), - }, - }, - }) -} - -//This is a regression test around https://github.com/hashicorp/terraform/issues/6517 -//Because we use CreateOrUpdate, we were sending an empty password on update requests -func TestAccAzureRMVirtualMachine_updateMachineSize(t *testing.T) { - ri := acctest.RandInt() - preConfig := fmt.Sprintf(testAccAzureRMVirtualMachine_basicLinuxMachine, ri, ri, ri, ri, ri, ri, ri) - postConfig := fmt.Sprintf(testAccAzureRMVirtualMachine_updatedLinuxMachine, ri, ri, ri, ri, ri, ri, ri) - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMVirtualMachineDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: preConfig, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test"), - resource.TestCheckResourceAttr( - "azurerm_virtual_machine.test", "vm_size", "Standard_A0"), - ), - }, - resource.TestStep{ - Config: postConfig, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test"), - resource.TestCheckResourceAttr( - "azurerm_virtual_machine.test", "vm_size", "Standard_A1"), - ), - }, - }, - }) -} - -func TestAccAzureRMVirtualMachine_basicWindowsMachine(t *testing.T) { - ri := acctest.RandInt() - config := fmt.Sprintf(testAccAzureRMVirtualMachine_basicWindowsMachine, ri, ri, ri, ri, ri, ri) - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testCheckAzureRMVirtualMachineDestroy, - Steps: []resource.TestStep{ - resource.TestStep{ - Config: config, - Check: resource.ComposeTestCheckFunc( - testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test"), - ), - }, - }, - }) -} - -func testCheckAzureRMVirtualMachineExists(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) - } - - vmName := rs.Primary.Attributes["name"] - resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] - if !hasResourceGroup { - return fmt.Errorf("Bad: no resource group found in state for virtual machine: %s", vmName) - } - - conn := testAccProvider.Meta().(*ArmClient).vmClient - - resp, err := conn.Get(resourceGroup, vmName, "") - if err != nil { - return fmt.Errorf("Bad: Get on vmClient: %s", err) - } - - if resp.StatusCode == http.StatusNotFound { - return fmt.Errorf("Bad: VirtualMachine %q (resource group: %q) does not exist", vmName, resourceGroup) - } - - return nil - } -} - -func testCheckAzureRMVirtualMachineDestroy(s *terraform.State) error { - conn := testAccProvider.Meta().(*ArmClient).vmClient - - for _, rs := range s.RootModule().Resources { - if rs.Type != "azurerm_virtual_machine" { - continue - } - - name := rs.Primary.Attributes["name"] - resourceGroup := rs.Primary.Attributes["resource_group_name"] - - resp, err := conn.Get(resourceGroup, name, "") - - if err != nil { - return nil - } - - if resp.StatusCode != http.StatusNotFound { - return fmt.Errorf("Virtual Machine still exists:\n%#v", resp.Properties) - } - } - - return nil -} - -var testAccAzureRMVirtualMachine_basicLinuxMachine = ` -resource "azurerm_resource_group" "test" { - name = "acctestrg-%d" - location = "West US" -} - -resource "azurerm_virtual_network" "test" { - name = "acctvn-%d" - address_space = ["10.0.0.0/16"] - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" -} - -resource "azurerm_subnet" "test" { - name = "acctsub-%d" - resource_group_name = "${azurerm_resource_group.test.name}" - virtual_network_name = "${azurerm_virtual_network.test.name}" - address_prefix = "10.0.2.0/24" -} - -resource "azurerm_network_interface" "test" { - name = "acctni-%d" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - - ip_configuration { - name = "testconfiguration1" - subnet_id = "${azurerm_subnet.test.id}" - private_ip_address_allocation = "dynamic" - } -} - -resource "azurerm_storage_account" "test" { - name = "accsa%d" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "westus" - account_type = "Standard_LRS" - - tags { - environment = "staging" - } -} - -resource "azurerm_storage_container" "test" { - name = "vhds" - resource_group_name = "${azurerm_resource_group.test.name}" - storage_account_name = "${azurerm_storage_account.test.name}" - container_access_type = "private" -} - -resource "azurerm_virtual_machine" "test" { - name = "acctvm-%d" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - network_interface_ids = ["${azurerm_network_interface.test.id}"] - vm_size = "Standard_A0" - - storage_image_reference { - publisher = "Canonical" - offer = "UbuntuServer" - sku = "14.04.2-LTS" - version = "latest" - } - - storage_os_disk { - name = "myosdisk1" - vhd_uri = "${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/myosdisk1.vhd" - caching = "ReadWrite" - create_option = "FromImage" - } - - os_profile { - computer_name = "hostname%d" - admin_username = "testadmin" - admin_password = "Password1234!" - } - - os_profile_linux_config { - disable_password_authentication = false - } - - tags { - environment = "Production" - cost-center = "Ops" - } -} -` - -var testAccAzureRMVirtualMachine_basicLinuxMachineUpdated = ` -resource "azurerm_resource_group" "test" { - name = "acctestrg-%d" - location = "West US" -} - -resource "azurerm_virtual_network" "test" { - name = "acctvn-%d" - address_space = ["10.0.0.0/16"] - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" -} - -resource "azurerm_subnet" "test" { - name = "acctsub-%d" - resource_group_name = "${azurerm_resource_group.test.name}" - virtual_network_name = "${azurerm_virtual_network.test.name}" - address_prefix = "10.0.2.0/24" -} - -resource "azurerm_network_interface" "test" { - name = "acctni-%d" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - - ip_configuration { - name = "testconfiguration1" - subnet_id = "${azurerm_subnet.test.id}" - private_ip_address_allocation = "dynamic" - } -} - -resource "azurerm_storage_account" "test" { - name = "accsa%d" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "westus" - account_type = "Standard_LRS" - - tags { - environment = "staging" - } -} - -resource "azurerm_storage_container" "test" { - name = "vhds" - resource_group_name = "${azurerm_resource_group.test.name}" - storage_account_name = "${azurerm_storage_account.test.name}" - container_access_type = "private" -} - -resource "azurerm_virtual_machine" "test" { - name = "acctvm-%d" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - network_interface_ids = ["${azurerm_network_interface.test.id}"] - vm_size = "Standard_A0" - - storage_image_reference { - publisher = "Canonical" - offer = "UbuntuServer" - sku = "14.04.2-LTS" - version = "latest" - } - - storage_os_disk { - name = "myosdisk1" - vhd_uri = "${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/myosdisk1.vhd" - caching = "ReadWrite" - create_option = "FromImage" - } - - os_profile { - computer_name = "hostname%d" - admin_username = "testadmin" - admin_password = "Password1234!" - } - - os_profile_linux_config { - disable_password_authentication = false - } - - tags { - environment = "Production" - } -} -` - -var testAccAzureRMVirtualMachine_updatedLinuxMachine = ` -resource "azurerm_resource_group" "test" { - name = "acctestrg-%d" - location = "West US" -} - -resource "azurerm_virtual_network" "test" { - name = "acctvn-%d" - address_space = ["10.0.0.0/16"] - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" -} - -resource "azurerm_subnet" "test" { - name = "acctsub-%d" - resource_group_name = "${azurerm_resource_group.test.name}" - virtual_network_name = "${azurerm_virtual_network.test.name}" - address_prefix = "10.0.2.0/24" -} - -resource "azurerm_network_interface" "test" { - name = "acctni-%d" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - - ip_configuration { - name = "testconfiguration1" - subnet_id = "${azurerm_subnet.test.id}" - private_ip_address_allocation = "dynamic" - } -} - -resource "azurerm_storage_account" "test" { - name = "accsa%d" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "westus" - account_type = "Standard_LRS" - - tags { - environment = "staging" - } -} - -resource "azurerm_storage_container" "test" { - name = "vhds" - resource_group_name = "${azurerm_resource_group.test.name}" - storage_account_name = "${azurerm_storage_account.test.name}" - container_access_type = "private" -} - -resource "azurerm_virtual_machine" "test" { - name = "acctvm-%d" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - network_interface_ids = ["${azurerm_network_interface.test.id}"] - vm_size = "Standard_A1" - - storage_image_reference { - publisher = "Canonical" - offer = "UbuntuServer" - sku = "14.04.2-LTS" - version = "latest" - } - - storage_os_disk { - name = "myosdisk1" - vhd_uri = "${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/myosdisk1.vhd" - caching = "ReadWrite" - create_option = "FromImage" - } - - os_profile { - computer_name = "hostname%d" - admin_username = "testadmin" - admin_password = "Password1234!" - } - - os_profile_linux_config { - disable_password_authentication = false - } -} -` - -var testAccAzureRMVirtualMachine_basicWindowsMachine = ` -resource "azurerm_resource_group" "test" { - name = "acctestrg-%d" - location = "West US" -} - -resource "azurerm_virtual_network" "test" { - name = "acctvn-%d" - address_space = ["10.0.0.0/16"] - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" -} - -resource "azurerm_subnet" "test" { - name = "acctsub-%d" - resource_group_name = "${azurerm_resource_group.test.name}" - virtual_network_name = "${azurerm_virtual_network.test.name}" - address_prefix = "10.0.2.0/24" -} - -resource "azurerm_network_interface" "test" { - name = "acctni-%d" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - - ip_configuration { - name = "testconfiguration1" - subnet_id = "${azurerm_subnet.test.id}" - private_ip_address_allocation = "dynamic" - } -} - -resource "azurerm_storage_account" "test" { - name = "accsa%d" - resource_group_name = "${azurerm_resource_group.test.name}" - location = "westus" - account_type = "Standard_LRS" - - tags { - environment = "staging" - } -} - -resource "azurerm_storage_container" "test" { - name = "vhds" - resource_group_name = "${azurerm_resource_group.test.name}" - storage_account_name = "${azurerm_storage_account.test.name}" - container_access_type = "private" -} - -resource "azurerm_virtual_machine" "test" { - name = "acctvm-%d" - location = "West US" - resource_group_name = "${azurerm_resource_group.test.name}" - network_interface_ids = ["${azurerm_network_interface.test.id}"] - vm_size = "Standard_A0" - - storage_image_reference { - publisher = "MicrosoftWindowsServer" - offer = "WindowsServer" - sku = "2012-Datacenter" - version = "latest" - } - - storage_os_disk { - name = "myosdisk1" - vhd_uri = "${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/myosdisk1.vhd" - caching = "ReadWrite" - create_option = "FromImage" - } - - os_profile { - computer_name = "winhost01" - admin_username = "testadmin" - admin_password = "Password1234!" - } - - os_profile_windows_config { - enable_automatic_upgrades = false - provision_vm_agent = true - } -} -` +//import ( +// "fmt" +// "net/http" +// "testing" +// +// "github.com/hashicorp/terraform/helper/acctest" +// "github.com/hashicorp/terraform/helper/resource" +// "github.com/hashicorp/terraform/terraform" +//) +// +//func TestAccAzureRMVirtualMachine_basicLinuxMachine(t *testing.T) { +// ri := acctest.RandInt() +// config := fmt.Sprintf(testAccAzureRMVirtualMachine_basicLinuxMachine, ri, ri, ri, ri, ri, ri, ri) +// resource.Test(t, resource.TestCase{ +// PreCheck: func() { testAccPreCheck(t) }, +// Providers: testAccProviders, +// CheckDestroy: testCheckAzureRMVirtualMachineDestroy, +// Steps: []resource.TestStep{ +// resource.TestStep{ +// Config: config, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test"), +// ), +// }, +// }, +// }) +//} +// +//func TestAccAzureRMVirtualMachine_tags(t *testing.T) { +// ri := acctest.RandInt() +// preConfig := fmt.Sprintf(testAccAzureRMVirtualMachine_basicLinuxMachine, ri, ri, ri, ri, ri, ri, ri) +// postConfig := fmt.Sprintf(testAccAzureRMVirtualMachine_basicLinuxMachineUpdated, ri, ri, ri, ri, ri, ri, ri) +// resource.Test(t, resource.TestCase{ +// PreCheck: func() { testAccPreCheck(t) }, +// Providers: testAccProviders, +// CheckDestroy: testCheckAzureRMVirtualMachineDestroy, +// Steps: []resource.TestStep{ +// resource.TestStep{ +// Config: preConfig, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test"), +// resource.TestCheckResourceAttr( +// "azurerm_virtual_machine.test", "tags.#", "2"), +// resource.TestCheckResourceAttr( +// "azurerm_virtual_machine.test", "tags.environment", "Production"), +// resource.TestCheckResourceAttr( +// "azurerm_virtual_machine.test", "tags.cost-center", "Ops"), +// ), +// }, +// +// resource.TestStep{ +// Config: postConfig, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test"), +// resource.TestCheckResourceAttr( +// "azurerm_virtual_machine.test", "tags.#", "1"), +// resource.TestCheckResourceAttr( +// "azurerm_virtual_machine.test", "tags.environment", "Production"), +// ), +// }, +// }, +// }) +//} +// +////This is a regression test around https://github.com/hashicorp/terraform/issues/6517 +////Because we use CreateOrUpdate, we were sending an empty password on update requests +//func TestAccAzureRMVirtualMachine_updateMachineSize(t *testing.T) { +// ri := acctest.RandInt() +// preConfig := fmt.Sprintf(testAccAzureRMVirtualMachine_basicLinuxMachine, ri, ri, ri, ri, ri, ri, ri) +// postConfig := fmt.Sprintf(testAccAzureRMVirtualMachine_updatedLinuxMachine, ri, ri, ri, ri, ri, ri, ri) +// resource.Test(t, resource.TestCase{ +// PreCheck: func() { testAccPreCheck(t) }, +// Providers: testAccProviders, +// CheckDestroy: testCheckAzureRMVirtualMachineDestroy, +// Steps: []resource.TestStep{ +// resource.TestStep{ +// Config: preConfig, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test"), +// resource.TestCheckResourceAttr( +// "azurerm_virtual_machine.test", "vm_size", "Standard_A0"), +// ), +// }, +// resource.TestStep{ +// Config: postConfig, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test"), +// resource.TestCheckResourceAttr( +// "azurerm_virtual_machine.test", "vm_size", "Standard_A1"), +// ), +// }, +// }, +// }) +//} +// +//func TestAccAzureRMVirtualMachine_basicWindowsMachine(t *testing.T) { +// ri := acctest.RandInt() +// config := fmt.Sprintf(testAccAzureRMVirtualMachine_basicWindowsMachine, ri, ri, ri, ri, ri, ri) +// resource.Test(t, resource.TestCase{ +// PreCheck: func() { testAccPreCheck(t) }, +// Providers: testAccProviders, +// CheckDestroy: testCheckAzureRMVirtualMachineDestroy, +// Steps: []resource.TestStep{ +// resource.TestStep{ +// Config: config, +// Check: resource.ComposeTestCheckFunc( +// testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test"), +// ), +// }, +// }, +// }) +//} +// +//func testCheckAzureRMVirtualMachineExists(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) +// } +// +// vmName := rs.Primary.Attributes["name"] +// resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] +// if !hasResourceGroup { +// return fmt.Errorf("Bad: no resource group found in state for virtual machine: %s", vmName) +// } +// +// conn := testAccProvider.Meta().(*ArmClient).vmClient +// +// resp, err := conn.Get(resourceGroup, vmName, "") +// if err != nil { +// return fmt.Errorf("Bad: Get on vmClient: %s", err) +// } +// +// if resp.StatusCode == http.StatusNotFound { +// return fmt.Errorf("Bad: VirtualMachine %q (resource group: %q) does not exist", vmName, resourceGroup) +// } +// +// return nil +// } +//} +// +//func testCheckAzureRMVirtualMachineDestroy(s *terraform.State) error { +// conn := testAccProvider.Meta().(*ArmClient).vmClient +// +// for _, rs := range s.RootModule().Resources { +// if rs.Type != "azurerm_virtual_machine" { +// continue +// } +// +// name := rs.Primary.Attributes["name"] +// resourceGroup := rs.Primary.Attributes["resource_group_name"] +// +// resp, err := conn.Get(resourceGroup, name, "") +// +// if err != nil { +// return nil +// } +// +// if resp.StatusCode != http.StatusNotFound { +// return fmt.Errorf("Virtual Machine still exists:\n%#v", resp.Properties) +// } +// } +// +// return nil +//} +// +//var testAccAzureRMVirtualMachine_basicLinuxMachine = ` +//resource "azurerm_resource_group" "test" { +// name = "acctestrg-%d" +// location = "West US" +//} +// +//resource "azurerm_virtual_network" "test" { +// name = "acctvn-%d" +// address_space = ["10.0.0.0/16"] +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +//} +// +//resource "azurerm_subnet" "test" { +// name = "acctsub-%d" +// resource_group_name = "${azurerm_resource_group.test.name}" +// virtual_network_name = "${azurerm_virtual_network.test.name}" +// address_prefix = "10.0.2.0/24" +//} +// +//resource "azurerm_network_interface" "test" { +// name = "acctni-%d" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// +// ip_configuration { +// name = "testconfiguration1" +// subnet_id = "${azurerm_subnet.test.id}" +// private_ip_address_allocation = "dynamic" +// } +//} +// +//resource "azurerm_storage_account" "test" { +// name = "accsa%d" +// resource_group_name = "${azurerm_resource_group.test.name}" +// location = "westus" +// account_type = "Standard_LRS" +// +// tags { +// environment = "staging" +// } +//} +// +//resource "azurerm_storage_container" "test" { +// name = "vhds" +// resource_group_name = "${azurerm_resource_group.test.name}" +// storage_account_name = "${azurerm_storage_account.test.name}" +// container_access_type = "private" +//} +// +//resource "azurerm_virtual_machine" "test" { +// name = "acctvm-%d" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// network_interface_ids = ["${azurerm_network_interface.test.id}"] +// vm_size = "Standard_A0" +// +// storage_image_reference { +// publisher = "Canonical" +// offer = "UbuntuServer" +// sku = "14.04.2-LTS" +// version = "latest" +// } +// +// storage_os_disk { +// name = "myosdisk1" +// vhd_uri = "${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/myosdisk1.vhd" +// caching = "ReadWrite" +// create_option = "FromImage" +// } +// +// os_profile { +// computer_name = "hostname%d" +// admin_username = "testadmin" +// admin_password = "Password1234!" +// } +// +// os_profile_linux_config { +// disable_password_authentication = false +// } +// +// tags { +// environment = "Production" +// cost-center = "Ops" +// } +//} +//` +// +//var testAccAzureRMVirtualMachine_basicLinuxMachineUpdated = ` +//resource "azurerm_resource_group" "test" { +// name = "acctestrg-%d" +// location = "West US" +//} +// +//resource "azurerm_virtual_network" "test" { +// name = "acctvn-%d" +// address_space = ["10.0.0.0/16"] +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +//} +// +//resource "azurerm_subnet" "test" { +// name = "acctsub-%d" +// resource_group_name = "${azurerm_resource_group.test.name}" +// virtual_network_name = "${azurerm_virtual_network.test.name}" +// address_prefix = "10.0.2.0/24" +//} +// +//resource "azurerm_network_interface" "test" { +// name = "acctni-%d" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// +// ip_configuration { +// name = "testconfiguration1" +// subnet_id = "${azurerm_subnet.test.id}" +// private_ip_address_allocation = "dynamic" +// } +//} +// +//resource "azurerm_storage_account" "test" { +// name = "accsa%d" +// resource_group_name = "${azurerm_resource_group.test.name}" +// location = "westus" +// account_type = "Standard_LRS" +// +// tags { +// environment = "staging" +// } +//} +// +//resource "azurerm_storage_container" "test" { +// name = "vhds" +// resource_group_name = "${azurerm_resource_group.test.name}" +// storage_account_name = "${azurerm_storage_account.test.name}" +// container_access_type = "private" +//} +// +//resource "azurerm_virtual_machine" "test" { +// name = "acctvm-%d" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// network_interface_ids = ["${azurerm_network_interface.test.id}"] +// vm_size = "Standard_A0" +// +// storage_image_reference { +// publisher = "Canonical" +// offer = "UbuntuServer" +// sku = "14.04.2-LTS" +// version = "latest" +// } +// +// storage_os_disk { +// name = "myosdisk1" +// vhd_uri = "${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/myosdisk1.vhd" +// caching = "ReadWrite" +// create_option = "FromImage" +// } +// +// os_profile { +// computer_name = "hostname%d" +// admin_username = "testadmin" +// admin_password = "Password1234!" +// } +// +// os_profile_linux_config { +// disable_password_authentication = false +// } +// +// tags { +// environment = "Production" +// } +//} +//` +// +//var testAccAzureRMVirtualMachine_updatedLinuxMachine = ` +//resource "azurerm_resource_group" "test" { +// name = "acctestrg-%d" +// location = "West US" +//} +// +//resource "azurerm_virtual_network" "test" { +// name = "acctvn-%d" +// address_space = ["10.0.0.0/16"] +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +//} +// +//resource "azurerm_subnet" "test" { +// name = "acctsub-%d" +// resource_group_name = "${azurerm_resource_group.test.name}" +// virtual_network_name = "${azurerm_virtual_network.test.name}" +// address_prefix = "10.0.2.0/24" +//} +// +//resource "azurerm_network_interface" "test" { +// name = "acctni-%d" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// +// ip_configuration { +// name = "testconfiguration1" +// subnet_id = "${azurerm_subnet.test.id}" +// private_ip_address_allocation = "dynamic" +// } +//} +// +//resource "azurerm_storage_account" "test" { +// name = "accsa%d" +// resource_group_name = "${azurerm_resource_group.test.name}" +// location = "westus" +// account_type = "Standard_LRS" +// +// tags { +// environment = "staging" +// } +//} +// +//resource "azurerm_storage_container" "test" { +// name = "vhds" +// resource_group_name = "${azurerm_resource_group.test.name}" +// storage_account_name = "${azurerm_storage_account.test.name}" +// container_access_type = "private" +//} +// +//resource "azurerm_virtual_machine" "test" { +// name = "acctvm-%d" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// network_interface_ids = ["${azurerm_network_interface.test.id}"] +// vm_size = "Standard_A1" +// +// storage_image_reference { +// publisher = "Canonical" +// offer = "UbuntuServer" +// sku = "14.04.2-LTS" +// version = "latest" +// } +// +// storage_os_disk { +// name = "myosdisk1" +// vhd_uri = "${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/myosdisk1.vhd" +// caching = "ReadWrite" +// create_option = "FromImage" +// } +// +// os_profile { +// computer_name = "hostname%d" +// admin_username = "testadmin" +// admin_password = "Password1234!" +// } +// +// os_profile_linux_config { +// disable_password_authentication = false +// } +//} +//` +// +//var testAccAzureRMVirtualMachine_basicWindowsMachine = ` +//resource "azurerm_resource_group" "test" { +// name = "acctestrg-%d" +// location = "West US" +//} +// +//resource "azurerm_virtual_network" "test" { +// name = "acctvn-%d" +// address_space = ["10.0.0.0/16"] +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +//} +// +//resource "azurerm_subnet" "test" { +// name = "acctsub-%d" +// resource_group_name = "${azurerm_resource_group.test.name}" +// virtual_network_name = "${azurerm_virtual_network.test.name}" +// address_prefix = "10.0.2.0/24" +//} +// +//resource "azurerm_network_interface" "test" { +// name = "acctni-%d" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// +// ip_configuration { +// name = "testconfiguration1" +// subnet_id = "${azurerm_subnet.test.id}" +// private_ip_address_allocation = "dynamic" +// } +//} +// +//resource "azurerm_storage_account" "test" { +// name = "accsa%d" +// resource_group_name = "${azurerm_resource_group.test.name}" +// location = "westus" +// account_type = "Standard_LRS" +// +// tags { +// environment = "staging" +// } +//} +// +//resource "azurerm_storage_container" "test" { +// name = "vhds" +// resource_group_name = "${azurerm_resource_group.test.name}" +// storage_account_name = "${azurerm_storage_account.test.name}" +// container_access_type = "private" +//} +// +//resource "azurerm_virtual_machine" "test" { +// name = "acctvm-%d" +// location = "West US" +// resource_group_name = "${azurerm_resource_group.test.name}" +// network_interface_ids = ["${azurerm_network_interface.test.id}"] +// vm_size = "Standard_A0" +// +// storage_image_reference { +// publisher = "MicrosoftWindowsServer" +// offer = "WindowsServer" +// sku = "2012-Datacenter" +// version = "latest" +// } +// +// storage_os_disk { +// name = "myosdisk1" +// vhd_uri = "${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/myosdisk1.vhd" +// caching = "ReadWrite" +// create_option = "FromImage" +// } +// +// os_profile { +// computer_name = "winhost01" +// admin_username = "testadmin" +// admin_password = "Password1234!" +// } +// +// os_profile_windows_config { +// enable_automatic_upgrades = false +// provision_vm_agent = true +// } +//} +//` diff --git a/builtin/providers/azurerm/resource_arm_virtual_network.go b/builtin/providers/azurerm/resource_arm_virtual_network.go index c6b469907111..fb1248db8939 100644 --- a/builtin/providers/azurerm/resource_arm_virtual_network.go +++ b/builtin/providers/azurerm/resource_arm_virtual_network.go @@ -1,257 +1,257 @@ package azurerm -import ( - "fmt" - "log" - "net/http" - "time" - - "github.com/Azure/azure-sdk-for-go/arm/network" - "github.com/hashicorp/terraform/helper/hashcode" - "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/helper/schema" -) - -func resourceArmVirtualNetwork() *schema.Resource { - return &schema.Resource{ - Create: resourceArmVirtualNetworkCreate, - Read: resourceArmVirtualNetworkRead, - Update: resourceArmVirtualNetworkCreate, - Delete: resourceArmVirtualNetworkDelete, - - Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - - "address_space": &schema.Schema{ - Type: schema.TypeList, - Required: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - - "dns_servers": &schema.Schema{ - Type: schema.TypeList, - Optional: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - - "subnet": &schema.Schema{ - Type: schema.TypeSet, - Optional: true, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - "address_prefix": &schema.Schema{ - Type: schema.TypeString, - Required: true, - }, - "security_group": &schema.Schema{ - Type: schema.TypeString, - Optional: true, - }, - }, - }, - Set: resourceAzureSubnetHash, - }, - - "location": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - StateFunc: azureRMNormalizeLocation, - }, - - "resource_group_name": &schema.Schema{ - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - - "tags": tagsSchema(), - }, - } -} - -func resourceArmVirtualNetworkCreate(d *schema.ResourceData, meta interface{}) error { - client := meta.(*ArmClient) - vnetClient := client.vnetClient - - log.Printf("[INFO] preparing arguments for Azure ARM virtual network creation.") - - name := d.Get("name").(string) - location := d.Get("location").(string) - resGroup := d.Get("resource_group_name").(string) - tags := d.Get("tags").(map[string]interface{}) - - vnet := network.VirtualNetwork{ - Name: &name, - Location: &location, - Properties: getVirtualNetworkProperties(d), - Tags: expandTags(tags), - } - - resp, err := vnetClient.CreateOrUpdate(resGroup, name, vnet) - if err != nil { - return err - } - - d.SetId(*resp.ID) - - log.Printf("[DEBUG] Waiting for Virtual Network (%s) to become available", name) - stateConf := &resource.StateChangeConf{ - Pending: []string{"Accepted", "Updating"}, - Target: []string{"Succeeded"}, - Refresh: virtualNetworkStateRefreshFunc(client, resGroup, name), - Timeout: 10 * time.Minute, - } - if _, err := stateConf.WaitForState(); err != nil { - return fmt.Errorf("Error waiting for Virtual Network (%s) to become available: %s", name, err) - } - - return resourceArmVirtualNetworkRead(d, meta) -} - -func resourceArmVirtualNetworkRead(d *schema.ResourceData, meta interface{}) error { - vnetClient := meta.(*ArmClient).vnetClient - - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - resGroup := id.ResourceGroup - name := id.Path["virtualNetworks"] - - resp, err := vnetClient.Get(resGroup, name, "") - if resp.StatusCode == http.StatusNotFound { - d.SetId("") - return nil - } - if err != nil { - return fmt.Errorf("Error making Read request on Azure virtual network %s: %s", name, err) - } - vnet := *resp.Properties - - // update appropriate values - d.Set("address_space", vnet.AddressSpace.AddressPrefixes) - - subnets := &schema.Set{ - F: resourceAzureSubnetHash, - } - - for _, subnet := range *vnet.Subnets { - s := map[string]interface{}{} - - s["name"] = *subnet.Name - s["address_prefix"] = *subnet.Properties.AddressPrefix - if subnet.Properties.NetworkSecurityGroup != nil { - s["security_group"] = *subnet.Properties.NetworkSecurityGroup.ID - } - - subnets.Add(s) - } - d.Set("subnet", subnets) - - dnses := []string{} - for _, dns := range *vnet.DhcpOptions.DNSServers { - dnses = append(dnses, dns) - } - d.Set("dns_servers", dnses) - - flattenAndSetTags(d, resp.Tags) - - return nil -} - -func resourceArmVirtualNetworkDelete(d *schema.ResourceData, meta interface{}) error { - vnetClient := meta.(*ArmClient).vnetClient - - id, err := parseAzureResourceID(d.Id()) - if err != nil { - return err - } - resGroup := id.ResourceGroup - name := id.Path["virtualNetworks"] - - _, err = vnetClient.Delete(resGroup, name) - - return err -} - -func getVirtualNetworkProperties(d *schema.ResourceData) *network.VirtualNetworkPropertiesFormat { - // first; get address space prefixes: - prefixes := []string{} - for _, prefix := range d.Get("address_space").([]interface{}) { - prefixes = append(prefixes, prefix.(string)) - } - - // then; the dns servers: - dnses := []string{} - for _, dns := range d.Get("dns_servers").([]interface{}) { - dnses = append(dnses, dns.(string)) - } - - // then; the subnets: - subnets := []network.Subnet{} - if subs := d.Get("subnet").(*schema.Set); subs.Len() > 0 { - for _, subnet := range subs.List() { - subnet := subnet.(map[string]interface{}) - - name := subnet["name"].(string) - prefix := subnet["address_prefix"].(string) - secGroup := subnet["security_group"].(string) - - var subnetObj network.Subnet - subnetObj.Name = &name - subnetObj.Properties = &network.SubnetPropertiesFormat{} - subnetObj.Properties.AddressPrefix = &prefix - - if secGroup != "" { - subnetObj.Properties.NetworkSecurityGroup = &network.SecurityGroup{ - ID: &secGroup, - } - } - - subnets = append(subnets, subnetObj) - } - } - - // finally; return the struct: - return &network.VirtualNetworkPropertiesFormat{ - AddressSpace: &network.AddressSpace{ - AddressPrefixes: &prefixes, - }, - DhcpOptions: &network.DhcpOptions{ - DNSServers: &dnses, - }, - Subnets: &subnets, - } -} - -func resourceAzureSubnetHash(v interface{}) int { - m := v.(map[string]interface{}) - subnet := m["name"].(string) + m["address_prefix"].(string) - if securityGroup, present := m["security_group"]; present { - subnet = subnet + securityGroup.(string) - } - return hashcode.String(subnet) -} - -func virtualNetworkStateRefreshFunc(client *ArmClient, resourceGroupName string, networkName string) resource.StateRefreshFunc { - return func() (interface{}, string, error) { - res, err := client.vnetClient.Get(resourceGroupName, networkName, "") - if err != nil { - return nil, "", fmt.Errorf("Error issuing read request in virtualNetworkStateRefreshFunc to Azure ARM for virtual network '%s' (RG: '%s'): %s", networkName, resourceGroupName, err) - } - - return res, *res.Properties.ProvisioningState, nil - } -} +//import ( +// "fmt" +// "log" +// "net/http" +// "time" +// +// "github.com/Azure/azure-sdk-for-go/arm/network" +// "github.com/hashicorp/terraform/helper/hashcode" +// "github.com/hashicorp/terraform/helper/resource" +// "github.com/hashicorp/terraform/helper/schema" +//) +// +//func resourceArmVirtualNetwork() *schema.Resource { +// return &schema.Resource{ +// Create: resourceArmVirtualNetworkCreate, +// Read: resourceArmVirtualNetworkRead, +// Update: resourceArmVirtualNetworkCreate, +// Delete: resourceArmVirtualNetworkDelete, +// +// Schema: map[string]*schema.Schema{ +// "name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// }, +// +// "address_space": &schema.Schema{ +// Type: schema.TypeList, +// Required: true, +// Elem: &schema.Schema{Type: schema.TypeString}, +// }, +// +// "dns_servers": &schema.Schema{ +// Type: schema.TypeList, +// Optional: true, +// Elem: &schema.Schema{ +// Type: schema.TypeString, +// }, +// }, +// +// "subnet": &schema.Schema{ +// Type: schema.TypeSet, +// Optional: true, +// Computed: true, +// Elem: &schema.Resource{ +// Schema: map[string]*schema.Schema{ +// "name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// "address_prefix": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// }, +// "security_group": &schema.Schema{ +// Type: schema.TypeString, +// Optional: true, +// }, +// }, +// }, +// Set: resourceAzureSubnetHash, +// }, +// +// "location": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// StateFunc: azureRMNormalizeLocation, +// }, +// +// "resource_group_name": &schema.Schema{ +// Type: schema.TypeString, +// Required: true, +// ForceNew: true, +// }, +// +// "tags": tagsSchema(), +// }, +// } +//} +// +//func resourceArmVirtualNetworkCreate(d *schema.ResourceData, meta interface{}) error { +// client := meta.(*ArmClient) +// vnetClient := client.vnetClient +// +// log.Printf("[INFO] preparing arguments for Azure ARM virtual network creation.") +// +// name := d.Get("name").(string) +// location := d.Get("location").(string) +// resGroup := d.Get("resource_group_name").(string) +// tags := d.Get("tags").(map[string]interface{}) +// +// vnet := network.VirtualNetwork{ +// Name: &name, +// Location: &location, +// Properties: getVirtualNetworkProperties(d), +// Tags: expandTags(tags), +// } +// +// resp, err := vnetClient.CreateOrUpdate(resGroup, name, vnet) +// if err != nil { +// return err +// } +// +// d.SetId(*resp.ID) +// +// log.Printf("[DEBUG] Waiting for Virtual Network (%s) to become available", name) +// stateConf := &resource.StateChangeConf{ +// Pending: []string{"Accepted", "Updating"}, +// Target: []string{"Succeeded"}, +// Refresh: virtualNetworkStateRefreshFunc(client, resGroup, name), +// Timeout: 10 * time.Minute, +// } +// if _, err := stateConf.WaitForState(); err != nil { +// return fmt.Errorf("Error waiting for Virtual Network (%s) to become available: %s", name, err) +// } +// +// return resourceArmVirtualNetworkRead(d, meta) +//} +// +//func resourceArmVirtualNetworkRead(d *schema.ResourceData, meta interface{}) error { +// vnetClient := meta.(*ArmClient).vnetClient +// +// id, err := parseAzureResourceID(d.Id()) +// if err != nil { +// return err +// } +// resGroup := id.ResourceGroup +// name := id.Path["virtualNetworks"] +// +// resp, err := vnetClient.Get(resGroup, name, "") +// if resp.StatusCode == http.StatusNotFound { +// d.SetId("") +// return nil +// } +// if err != nil { +// return fmt.Errorf("Error making Read request on Azure virtual network %s: %s", name, err) +// } +// vnet := *resp.Properties +// +// // update appropriate values +// d.Set("address_space", vnet.AddressSpace.AddressPrefixes) +// +// subnets := &schema.Set{ +// F: resourceAzureSubnetHash, +// } +// +// for _, subnet := range *vnet.Subnets { +// s := map[string]interface{}{} +// +// s["name"] = *subnet.Name +// s["address_prefix"] = *subnet.Properties.AddressPrefix +// if subnet.Properties.NetworkSecurityGroup != nil { +// s["security_group"] = *subnet.Properties.NetworkSecurityGroup.ID +// } +// +// subnets.Add(s) +// } +// d.Set("subnet", subnets) +// +// dnses := []string{} +// for _, dns := range *vnet.DhcpOptions.DNSServers { +// dnses = append(dnses, dns) +// } +// d.Set("dns_servers", dnses) +// +// flattenAndSetTags(d, resp.Tags) +// +// return nil +//} +// +//func resourceArmVirtualNetworkDelete(d *schema.ResourceData, meta interface{}) error { +// vnetClient := meta.(*ArmClient).vnetClient +// +// id, err := parseAzureResourceID(d.Id()) +// if err != nil { +// return err +// } +// resGroup := id.ResourceGroup +// name := id.Path["virtualNetworks"] +// +// _, err = vnetClient.Delete(resGroup, name) +// +// return err +//} +// +//func getVirtualNetworkProperties(d *schema.ResourceData) *network.VirtualNetworkPropertiesFormat { +// // first; get address space prefixes: +// prefixes := []string{} +// for _, prefix := range d.Get("address_space").([]interface{}) { +// prefixes = append(prefixes, prefix.(string)) +// } +// +// // then; the dns servers: +// dnses := []string{} +// for _, dns := range d.Get("dns_servers").([]interface{}) { +// dnses = append(dnses, dns.(string)) +// } +// +// // then; the subnets: +// subnets := []network.Subnet{} +// if subs := d.Get("subnet").(*schema.Set); subs.Len() > 0 { +// for _, subnet := range subs.List() { +// subnet := subnet.(map[string]interface{}) +// +// name := subnet["name"].(string) +// prefix := subnet["address_prefix"].(string) +// secGroup := subnet["security_group"].(string) +// +// var subnetObj network.Subnet +// subnetObj.Name = &name +// subnetObj.Properties = &network.SubnetPropertiesFormat{} +// subnetObj.Properties.AddressPrefix = &prefix +// +// if secGroup != "" { +// subnetObj.Properties.NetworkSecurityGroup = &network.SecurityGroup{ +// ID: &secGroup, +// } +// } +// +// subnets = append(subnets, subnetObj) +// } +// } +// +// // finally; return the struct: +// return &network.VirtualNetworkPropertiesFormat{ +// AddressSpace: &network.AddressSpace{ +// AddressPrefixes: &prefixes, +// }, +// DhcpOptions: &network.DhcpOptions{ +// DNSServers: &dnses, +// }, +// Subnets: &subnets, +// } +//} +// +//func resourceAzureSubnetHash(v interface{}) int { +// m := v.(map[string]interface{}) +// subnet := m["name"].(string) + m["address_prefix"].(string) +// if securityGroup, present := m["security_group"]; present { +// subnet = subnet + securityGroup.(string) +// } +// return hashcode.String(subnet) +//} +// +//func virtualNetworkStateRefreshFunc(client *ArmClient, resourceGroupName string, networkName string) resource.StateRefreshFunc { +// return func() (interface{}, string, error) { +// res, err := client.vnetClient.Get(resourceGroupName, networkName, "") +// if err != nil { +// return nil, "", fmt.Errorf("Error issuing read request in virtualNetworkStateRefreshFunc to Azure ARM for virtual network '%s' (RG: '%s'): %s", networkName, resourceGroupName, err) +// } +// +// return res, *res.Properties.ProvisioningState, nil +// } +//} From 36a204506f627b27c616c37c0bad97aaca5b0ebb Mon Sep 17 00:00:00 2001 From: James Nugent Date: Wed, 1 Jun 2016 16:36:41 -0500 Subject: [PATCH 03/17] provider/azurerm: Fix azurerm_virtual_network ``` make testacc TEST=./builtin/providers/azurerm TESTARGS="-run TestAccAzureRMVirtualNetwork" ==> Checking that code complies with gofmt requirements... /Users/James/Code/go/bin/stringer go generate $(go list ./... | grep -v /vendor/) 2016/06/01 16:19:17 Generated command/internal_plugin_list.go TF_ACC=1 go test ./builtin/providers/azurerm -v -run TestAccAzureRMVirtualNetwork -timeout 120m === RUN TestAccAzureRMVirtualNetwork_basic --- PASS: TestAccAzureRMVirtualNetwork_basic (206.36s) === RUN TestAccAzureRMVirtualNetwork_withTags --- PASS: TestAccAzureRMVirtualNetwork_withTags (289.05s) PASS ok github.com/hashicorp/terraform/builtin/providers/azurerm 495.422s ``` --- builtin/providers/azurerm/provider.go | 2 +- .../azurerm/resource_arm_virtual_network.go | 508 +++++++++--------- 2 files changed, 254 insertions(+), 256 deletions(-) diff --git a/builtin/providers/azurerm/provider.go b/builtin/providers/azurerm/provider.go index 4709d95a414c..a69111aaa1ef 100644 --- a/builtin/providers/azurerm/provider.go +++ b/builtin/providers/azurerm/provider.go @@ -62,7 +62,7 @@ func Provider() terraform.ResourceProvider { //"azurerm_subnet": resourceArmSubnet(), //"azurerm_template_deployment": resourceArmTemplateDeployment(), //"azurerm_virtual_machine": resourceArmVirtualMachine(), - //"azurerm_virtual_network": resourceArmVirtualNetwork(), + "azurerm_virtual_network": resourceArmVirtualNetwork(), // These resources use the Riviera SDK "azurerm_dns_a_record": resourceArmDnsARecord(), diff --git a/builtin/providers/azurerm/resource_arm_virtual_network.go b/builtin/providers/azurerm/resource_arm_virtual_network.go index fb1248db8939..312cdf02148e 100644 --- a/builtin/providers/azurerm/resource_arm_virtual_network.go +++ b/builtin/providers/azurerm/resource_arm_virtual_network.go @@ -1,257 +1,255 @@ package azurerm -//import ( -// "fmt" -// "log" -// "net/http" -// "time" -// -// "github.com/Azure/azure-sdk-for-go/arm/network" -// "github.com/hashicorp/terraform/helper/hashcode" -// "github.com/hashicorp/terraform/helper/resource" -// "github.com/hashicorp/terraform/helper/schema" -//) -// -//func resourceArmVirtualNetwork() *schema.Resource { -// return &schema.Resource{ -// Create: resourceArmVirtualNetworkCreate, -// Read: resourceArmVirtualNetworkRead, -// Update: resourceArmVirtualNetworkCreate, -// Delete: resourceArmVirtualNetworkDelete, -// -// Schema: map[string]*schema.Schema{ -// "name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// }, -// -// "address_space": &schema.Schema{ -// Type: schema.TypeList, -// Required: true, -// Elem: &schema.Schema{Type: schema.TypeString}, -// }, -// -// "dns_servers": &schema.Schema{ -// Type: schema.TypeList, -// Optional: true, -// Elem: &schema.Schema{ -// Type: schema.TypeString, -// }, -// }, -// -// "subnet": &schema.Schema{ -// Type: schema.TypeSet, -// Optional: true, -// Computed: true, -// Elem: &schema.Resource{ -// Schema: map[string]*schema.Schema{ -// "name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// "address_prefix": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// "security_group": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// }, -// }, -// }, -// Set: resourceAzureSubnetHash, -// }, -// -// "location": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// StateFunc: azureRMNormalizeLocation, -// }, -// -// "resource_group_name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// }, -// -// "tags": tagsSchema(), -// }, -// } -//} -// -//func resourceArmVirtualNetworkCreate(d *schema.ResourceData, meta interface{}) error { -// client := meta.(*ArmClient) -// vnetClient := client.vnetClient -// -// log.Printf("[INFO] preparing arguments for Azure ARM virtual network creation.") -// -// name := d.Get("name").(string) -// location := d.Get("location").(string) -// resGroup := d.Get("resource_group_name").(string) -// tags := d.Get("tags").(map[string]interface{}) -// -// vnet := network.VirtualNetwork{ -// Name: &name, -// Location: &location, -// Properties: getVirtualNetworkProperties(d), -// Tags: expandTags(tags), -// } -// -// resp, err := vnetClient.CreateOrUpdate(resGroup, name, vnet) -// if err != nil { -// return err -// } -// -// d.SetId(*resp.ID) -// -// log.Printf("[DEBUG] Waiting for Virtual Network (%s) to become available", name) -// stateConf := &resource.StateChangeConf{ -// Pending: []string{"Accepted", "Updating"}, -// Target: []string{"Succeeded"}, -// Refresh: virtualNetworkStateRefreshFunc(client, resGroup, name), -// Timeout: 10 * time.Minute, -// } -// if _, err := stateConf.WaitForState(); err != nil { -// return fmt.Errorf("Error waiting for Virtual Network (%s) to become available: %s", name, err) -// } -// -// return resourceArmVirtualNetworkRead(d, meta) -//} -// -//func resourceArmVirtualNetworkRead(d *schema.ResourceData, meta interface{}) error { -// vnetClient := meta.(*ArmClient).vnetClient -// -// id, err := parseAzureResourceID(d.Id()) -// if err != nil { -// return err -// } -// resGroup := id.ResourceGroup -// name := id.Path["virtualNetworks"] -// -// resp, err := vnetClient.Get(resGroup, name, "") -// if resp.StatusCode == http.StatusNotFound { -// d.SetId("") -// return nil -// } -// if err != nil { -// return fmt.Errorf("Error making Read request on Azure virtual network %s: %s", name, err) -// } -// vnet := *resp.Properties -// -// // update appropriate values -// d.Set("address_space", vnet.AddressSpace.AddressPrefixes) -// -// subnets := &schema.Set{ -// F: resourceAzureSubnetHash, -// } -// -// for _, subnet := range *vnet.Subnets { -// s := map[string]interface{}{} -// -// s["name"] = *subnet.Name -// s["address_prefix"] = *subnet.Properties.AddressPrefix -// if subnet.Properties.NetworkSecurityGroup != nil { -// s["security_group"] = *subnet.Properties.NetworkSecurityGroup.ID -// } -// -// subnets.Add(s) -// } -// d.Set("subnet", subnets) -// -// dnses := []string{} -// for _, dns := range *vnet.DhcpOptions.DNSServers { -// dnses = append(dnses, dns) -// } -// d.Set("dns_servers", dnses) -// -// flattenAndSetTags(d, resp.Tags) -// -// return nil -//} -// -//func resourceArmVirtualNetworkDelete(d *schema.ResourceData, meta interface{}) error { -// vnetClient := meta.(*ArmClient).vnetClient -// -// id, err := parseAzureResourceID(d.Id()) -// if err != nil { -// return err -// } -// resGroup := id.ResourceGroup -// name := id.Path["virtualNetworks"] -// -// _, err = vnetClient.Delete(resGroup, name) -// -// return err -//} -// -//func getVirtualNetworkProperties(d *schema.ResourceData) *network.VirtualNetworkPropertiesFormat { -// // first; get address space prefixes: -// prefixes := []string{} -// for _, prefix := range d.Get("address_space").([]interface{}) { -// prefixes = append(prefixes, prefix.(string)) -// } -// -// // then; the dns servers: -// dnses := []string{} -// for _, dns := range d.Get("dns_servers").([]interface{}) { -// dnses = append(dnses, dns.(string)) -// } -// -// // then; the subnets: -// subnets := []network.Subnet{} -// if subs := d.Get("subnet").(*schema.Set); subs.Len() > 0 { -// for _, subnet := range subs.List() { -// subnet := subnet.(map[string]interface{}) -// -// name := subnet["name"].(string) -// prefix := subnet["address_prefix"].(string) -// secGroup := subnet["security_group"].(string) -// -// var subnetObj network.Subnet -// subnetObj.Name = &name -// subnetObj.Properties = &network.SubnetPropertiesFormat{} -// subnetObj.Properties.AddressPrefix = &prefix -// -// if secGroup != "" { -// subnetObj.Properties.NetworkSecurityGroup = &network.SecurityGroup{ -// ID: &secGroup, -// } -// } -// -// subnets = append(subnets, subnetObj) -// } -// } -// -// // finally; return the struct: -// return &network.VirtualNetworkPropertiesFormat{ -// AddressSpace: &network.AddressSpace{ -// AddressPrefixes: &prefixes, -// }, -// DhcpOptions: &network.DhcpOptions{ -// DNSServers: &dnses, -// }, -// Subnets: &subnets, -// } -//} -// -//func resourceAzureSubnetHash(v interface{}) int { -// m := v.(map[string]interface{}) -// subnet := m["name"].(string) + m["address_prefix"].(string) -// if securityGroup, present := m["security_group"]; present { -// subnet = subnet + securityGroup.(string) -// } -// return hashcode.String(subnet) -//} -// -//func virtualNetworkStateRefreshFunc(client *ArmClient, resourceGroupName string, networkName string) resource.StateRefreshFunc { -// return func() (interface{}, string, error) { -// res, err := client.vnetClient.Get(resourceGroupName, networkName, "") -// if err != nil { -// return nil, "", fmt.Errorf("Error issuing read request in virtualNetworkStateRefreshFunc to Azure ARM for virtual network '%s' (RG: '%s'): %s", networkName, resourceGroupName, err) -// } -// -// return res, *res.Properties.ProvisioningState, nil -// } -//} +import ( + "fmt" + "log" + "net/http" + + "github.com/Azure/azure-sdk-for-go/arm/network" + "github.com/hashicorp/terraform/helper/hashcode" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceArmVirtualNetwork() *schema.Resource { + return &schema.Resource{ + Create: resourceArmVirtualNetworkCreate, + Read: resourceArmVirtualNetworkRead, + Update: resourceArmVirtualNetworkCreate, + Delete: resourceArmVirtualNetworkDelete, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "address_space": { + Type: schema.TypeList, + Required: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + + "dns_servers": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + + "subnet": { + Type: schema.TypeSet, + Optional: true, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + }, + "address_prefix": { + Type: schema.TypeString, + Required: true, + }, + "security_group": { + Type: schema.TypeString, + Optional: true, + }, + }, + }, + Set: resourceAzureSubnetHash, + }, + + "location": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + StateFunc: azureRMNormalizeLocation, + }, + + "resource_group_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "tags": tagsSchema(), + }, + } +} + +func resourceArmVirtualNetworkCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient) + vnetClient := client.vnetClient + + log.Printf("[INFO] preparing arguments for Azure ARM virtual network creation.") + + name := d.Get("name").(string) + location := d.Get("location").(string) + resGroup := d.Get("resource_group_name").(string) + tags := d.Get("tags").(map[string]interface{}) + + vnet := network.VirtualNetwork{ + Name: &name, + Location: &location, + Properties: getVirtualNetworkProperties(d), + Tags: expandTags(tags), + } + + _, err := vnetClient.CreateOrUpdate(resGroup, name, vnet, make(chan struct{})) + if err != nil { + return err + } + + read, err := vnetClient.Get(resGroup, name, "") + if err != nil { + return err + } + if read.ID == nil { + return fmt.Errorf("Cannot read Virtual Network %s (resource group %s) ID", name, resGroup) + } + + d.SetId(*read.ID) + + return resourceArmVirtualNetworkRead(d, meta) +} + +func resourceArmVirtualNetworkRead(d *schema.ResourceData, meta interface{}) error { + vnetClient := meta.(*ArmClient).vnetClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + name := id.Path["virtualNetworks"] + + resp, err := vnetClient.Get(resGroup, name, "") + if resp.StatusCode == http.StatusNotFound { + d.SetId("") + return nil + } + if err != nil { + return fmt.Errorf("Error making Read request on Azure virtual network %s: %s", name, err) + } + vnet := *resp.Properties + + // update appropriate values + d.Set("address_space", vnet.AddressSpace.AddressPrefixes) + + subnets := &schema.Set{ + F: resourceAzureSubnetHash, + } + + for _, subnet := range *vnet.Subnets { + s := map[string]interface{}{} + + s["name"] = *subnet.Name + s["address_prefix"] = *subnet.Properties.AddressPrefix + if subnet.Properties.NetworkSecurityGroup != nil { + s["security_group"] = *subnet.Properties.NetworkSecurityGroup.ID + } + + subnets.Add(s) + } + d.Set("subnet", subnets) + + dnses := []string{} + for _, dns := range *vnet.DhcpOptions.DNSServers { + dnses = append(dnses, dns) + } + d.Set("dns_servers", dnses) + + flattenAndSetTags(d, resp.Tags) + + return nil +} + +func resourceArmVirtualNetworkDelete(d *schema.ResourceData, meta interface{}) error { + vnetClient := meta.(*ArmClient).vnetClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + name := id.Path["virtualNetworks"] + + _, err = vnetClient.Delete(resGroup, name, make(chan struct{})) + + return err +} + +func getVirtualNetworkProperties(d *schema.ResourceData) *network.VirtualNetworkPropertiesFormat { + // first; get address space prefixes: + prefixes := []string{} + for _, prefix := range d.Get("address_space").([]interface{}) { + prefixes = append(prefixes, prefix.(string)) + } + + // then; the dns servers: + dnses := []string{} + for _, dns := range d.Get("dns_servers").([]interface{}) { + dnses = append(dnses, dns.(string)) + } + + // then; the subnets: + subnets := []network.Subnet{} + if subs := d.Get("subnet").(*schema.Set); subs.Len() > 0 { + for _, subnet := range subs.List() { + subnet := subnet.(map[string]interface{}) + + name := subnet["name"].(string) + prefix := subnet["address_prefix"].(string) + secGroup := subnet["security_group"].(string) + + var subnetObj network.Subnet + subnetObj.Name = &name + subnetObj.Properties = &network.SubnetPropertiesFormat{} + subnetObj.Properties.AddressPrefix = &prefix + + if secGroup != "" { + subnetObj.Properties.NetworkSecurityGroup = &network.SecurityGroup{ + ID: &secGroup, + } + } + + subnets = append(subnets, subnetObj) + } + } + + // finally; return the struct: + return &network.VirtualNetworkPropertiesFormat{ + AddressSpace: &network.AddressSpace{ + AddressPrefixes: &prefixes, + }, + DhcpOptions: &network.DhcpOptions{ + DNSServers: &dnses, + }, + Subnets: &subnets, + } +} + +func resourceAzureSubnetHash(v interface{}) int { + m := v.(map[string]interface{}) + subnet := m["name"].(string) + m["address_prefix"].(string) + if securityGroup, present := m["security_group"]; present { + subnet = subnet + securityGroup.(string) + } + return hashcode.String(subnet) +} + +func virtualNetworkStateRefreshFunc(client *ArmClient, resourceGroupName string, networkName string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + res, err := client.vnetClient.Get(resourceGroupName, networkName, "") + if err != nil { + return nil, "", fmt.Errorf("Error issuing read request in virtualNetworkStateRefreshFunc to Azure ARM for virtual network '%s' (RG: '%s'): %s", networkName, resourceGroupName, err) + } + + return res, *res.Properties.ProvisioningState, nil + } +} From 876d0269dfe3dea7535d41496d9adc674fb5ebca Mon Sep 17 00:00:00 2001 From: James Nugent Date: Wed, 1 Jun 2016 16:57:13 -0500 Subject: [PATCH 04/17] provider/azurerm: Fix azurerm_subnet ``` make testacc TEST=./builtin/providers/azurerm TESTARGS="-run TestAccAzureRMSubnet" ==> Checking that code complies with gofmt requirements... /Users/James/Code/go/bin/stringer go generate $(go list ./... | grep -v /vendor/) 2016/06/01 16:54:37 Generated command/internal_plugin_list.go TF_ACC=1 go test ./builtin/providers/azurerm -v -run TestAccAzureRMSubnet -timeout 120m === RUN TestAccAzureRMSubnet_basic --- PASS: TestAccAzureRMSubnet_basic (131.83s) PASS ok github.com/hashicorp/terraform/builtin/providers/azurerm 131.844s ``` --- builtin/providers/azurerm/provider.go | 2 +- .../providers/azurerm/resource_arm_subnet.go | 368 +++++++++--------- .../azurerm/resource_arm_subnet_test.go | 212 +++++----- 3 files changed, 289 insertions(+), 293 deletions(-) diff --git a/builtin/providers/azurerm/provider.go b/builtin/providers/azurerm/provider.go index a69111aaa1ef..c82bf3991169 100644 --- a/builtin/providers/azurerm/provider.go +++ b/builtin/providers/azurerm/provider.go @@ -59,7 +59,7 @@ func Provider() terraform.ResourceProvider { "azurerm_storage_blob": resourceArmStorageBlob(), //"azurerm_storage_container": resourceArmStorageContainer(), "azurerm_storage_queue": resourceArmStorageQueue(), - //"azurerm_subnet": resourceArmSubnet(), + "azurerm_subnet": resourceArmSubnet(), //"azurerm_template_deployment": resourceArmTemplateDeployment(), //"azurerm_virtual_machine": resourceArmVirtualMachine(), "azurerm_virtual_network": resourceArmVirtualNetwork(), diff --git a/builtin/providers/azurerm/resource_arm_subnet.go b/builtin/providers/azurerm/resource_arm_subnet.go index 701fdf0fef69..a09b9cab27a0 100644 --- a/builtin/providers/azurerm/resource_arm_subnet.go +++ b/builtin/providers/azurerm/resource_arm_subnet.go @@ -1,188 +1,184 @@ package azurerm -//import ( -// "fmt" -// "log" -// "net/http" -// "time" -// -// "github.com/Azure/azure-sdk-for-go/arm/network" -// "github.com/hashicorp/terraform/helper/resource" -// "github.com/hashicorp/terraform/helper/schema" -//) -// -//func resourceArmSubnet() *schema.Resource { -// return &schema.Resource{ -// Create: resourceArmSubnetCreate, -// Read: resourceArmSubnetRead, -// Update: resourceArmSubnetCreate, -// Delete: resourceArmSubnetDelete, -// -// Schema: map[string]*schema.Schema{ -// "name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// }, -// -// "resource_group_name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// }, -// -// "virtual_network_name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// }, -// -// "address_prefix": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "network_security_group_id": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// Computed: true, -// }, -// -// "route_table_id": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// Computed: true, -// }, -// -// "ip_configurations": &schema.Schema{ -// Type: schema.TypeSet, -// Optional: true, -// Computed: true, -// Elem: &schema.Schema{Type: schema.TypeString}, -// Set: schema.HashString, -// }, -// }, -// } -//} -// -//func resourceArmSubnetCreate(d *schema.ResourceData, meta interface{}) error { -// client := meta.(*ArmClient) -// subnetClient := client.subnetClient -// -// log.Printf("[INFO] preparing arguments for Azure ARM Subnet creation.") -// -// name := d.Get("name").(string) -// vnetName := d.Get("virtual_network_name").(string) -// resGroup := d.Get("resource_group_name").(string) -// addressPrefix := d.Get("address_prefix").(string) -// -// armMutexKV.Lock(vnetName) -// defer armMutexKV.Unlock(vnetName) -// -// properties := network.SubnetPropertiesFormat{ -// AddressPrefix: &addressPrefix, -// } -// -// if v, ok := d.GetOk("network_security_group_id"); ok { -// nsgId := v.(string) -// properties.NetworkSecurityGroup = &network.SecurityGroup{ -// ID: &nsgId, -// } -// } -// -// if v, ok := d.GetOk("route_table_id"); ok { -// rtId := v.(string) -// properties.RouteTable = &network.RouteTable{ -// ID: &rtId, -// } -// } -// -// subnet := network.Subnet{ -// Name: &name, -// Properties: &properties, -// } -// -// resp, err := subnetClient.CreateOrUpdate(resGroup, vnetName, name, subnet) -// if err != nil { -// return err -// } -// -// d.SetId(*resp.ID) -// -// log.Printf("[DEBUG] Waiting for Subnet (%s) to become available", name) -// stateConf := &resource.StateChangeConf{ -// Pending: []string{"Accepted", "Updating"}, -// Target: []string{"Succeeded"}, -// Refresh: subnetRuleStateRefreshFunc(client, resGroup, vnetName, name), -// Timeout: 10 * time.Minute, -// } -// if _, err := stateConf.WaitForState(); err != nil { -// return fmt.Errorf("Error waiting for Subnet (%s) to become available: %s", name, err) -// } -// -// return resourceArmSubnetRead(d, meta) -//} -// -//func resourceArmSubnetRead(d *schema.ResourceData, meta interface{}) error { -// subnetClient := meta.(*ArmClient).subnetClient -// -// id, err := parseAzureResourceID(d.Id()) -// if err != nil { -// return err -// } -// resGroup := id.ResourceGroup -// vnetName := id.Path["virtualNetworks"] -// name := id.Path["subnets"] -// -// resp, err := subnetClient.Get(resGroup, vnetName, name, "") -// if resp.StatusCode == http.StatusNotFound { -// d.SetId("") -// return nil -// } -// if err != nil { -// return fmt.Errorf("Error making Read request on Azure Subnet %s: %s", name, err) -// } -// -// if resp.Properties.IPConfigurations != nil && len(*resp.Properties.IPConfigurations) > 0 { -// ips := make([]string, 0, len(*resp.Properties.IPConfigurations)) -// for _, ip := range *resp.Properties.IPConfigurations { -// ips = append(ips, *ip.ID) -// } -// -// if err := d.Set("ip_configurations", ips); err != nil { -// return err -// } -// } -// -// return nil -//} -// -//func resourceArmSubnetDelete(d *schema.ResourceData, meta interface{}) error { -// subnetClient := meta.(*ArmClient).subnetClient -// -// id, err := parseAzureResourceID(d.Id()) -// if err != nil { -// return err -// } -// resGroup := id.ResourceGroup -// name := id.Path["subnets"] -// vnetName := id.Path["virtualNetworks"] -// -// armMutexKV.Lock(vnetName) -// defer armMutexKV.Unlock(vnetName) -// -// _, err = subnetClient.Delete(resGroup, vnetName, name) -// -// return err -//} -// -//func subnetRuleStateRefreshFunc(client *ArmClient, resourceGroupName string, virtualNetworkName string, subnetName string) resource.StateRefreshFunc { -// return func() (interface{}, string, error) { -// res, err := client.subnetClient.Get(resourceGroupName, virtualNetworkName, subnetName, "") -// if err != nil { -// return nil, "", fmt.Errorf("Error issuing read request in subnetRuleStateRefreshFunc to Azure ARM for subnet '%s' (RG: '%s') (VNN: '%s'): %s", subnetName, resourceGroupName, virtualNetworkName, err) -// } -// -// return res, *res.Properties.ProvisioningState, nil -// } -//} +import ( + "fmt" + "log" + "net/http" + + "github.com/Azure/azure-sdk-for-go/arm/network" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceArmSubnet() *schema.Resource { + return &schema.Resource{ + Create: resourceArmSubnetCreate, + Read: resourceArmSubnetRead, + Update: resourceArmSubnetCreate, + Delete: resourceArmSubnetDelete, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "resource_group_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "virtual_network_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "address_prefix": { + Type: schema.TypeString, + Required: true, + }, + + "network_security_group_id": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + + "route_table_id": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + + "ip_configurations": { + Type: schema.TypeSet, + Optional: true, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + Set: schema.HashString, + }, + }, + } +} + +func resourceArmSubnetCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient) + subnetClient := client.subnetClient + + log.Printf("[INFO] preparing arguments for Azure ARM Subnet creation.") + + name := d.Get("name").(string) + vnetName := d.Get("virtual_network_name").(string) + resGroup := d.Get("resource_group_name").(string) + addressPrefix := d.Get("address_prefix").(string) + + armMutexKV.Lock(vnetName) + defer armMutexKV.Unlock(vnetName) + + properties := network.SubnetPropertiesFormat{ + AddressPrefix: &addressPrefix, + } + + if v, ok := d.GetOk("network_security_group_id"); ok { + nsgId := v.(string) + properties.NetworkSecurityGroup = &network.SecurityGroup{ + ID: &nsgId, + } + } + + if v, ok := d.GetOk("route_table_id"); ok { + rtId := v.(string) + properties.RouteTable = &network.RouteTable{ + ID: &rtId, + } + } + + subnet := network.Subnet{ + Name: &name, + Properties: &properties, + } + + _, err := subnetClient.CreateOrUpdate(resGroup, vnetName, name, subnet, make(chan struct{})) + if err != nil { + return err + } + + read, err := subnetClient.Get(resGroup, vnetName, name, "") + if err != nil { + return err + } + if read.ID == nil { + return fmt.Errorf("Cannot read Subnet %s/%s (resource group %s) ID", vnetName, name, resGroup) + } + + d.SetId(*read.ID) + + return resourceArmSubnetRead(d, meta) +} + +func resourceArmSubnetRead(d *schema.ResourceData, meta interface{}) error { + subnetClient := meta.(*ArmClient).subnetClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + vnetName := id.Path["virtualNetworks"] + name := id.Path["subnets"] + + resp, err := subnetClient.Get(resGroup, vnetName, name, "") + if resp.StatusCode == http.StatusNotFound { + d.SetId("") + return nil + } + if err != nil { + return fmt.Errorf("Error making Read request on Azure Subnet %s: %s", name, err) + } + + if resp.Properties.IPConfigurations != nil && len(*resp.Properties.IPConfigurations) > 0 { + ips := make([]string, 0, len(*resp.Properties.IPConfigurations)) + for _, ip := range *resp.Properties.IPConfigurations { + ips = append(ips, *ip.ID) + } + + if err := d.Set("ip_configurations", ips); err != nil { + return err + } + } + + return nil +} + +func resourceArmSubnetDelete(d *schema.ResourceData, meta interface{}) error { + subnetClient := meta.(*ArmClient).subnetClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + name := id.Path["subnets"] + vnetName := id.Path["virtualNetworks"] + + armMutexKV.Lock(vnetName) + defer armMutexKV.Unlock(vnetName) + + _, err = subnetClient.Delete(resGroup, vnetName, name, make(chan struct{})) + + return err +} + +func subnetRuleStateRefreshFunc(client *ArmClient, resourceGroupName string, virtualNetworkName string, subnetName string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + res, err := client.subnetClient.Get(resourceGroupName, virtualNetworkName, subnetName, "") + if err != nil { + return nil, "", fmt.Errorf("Error issuing read request in subnetRuleStateRefreshFunc to Azure ARM for subnet '%s' (RG: '%s') (VNN: '%s'): %s", subnetName, resourceGroupName, virtualNetworkName, err) + } + + return res, *res.Properties.ProvisioningState, nil + } +} diff --git a/builtin/providers/azurerm/resource_arm_subnet_test.go b/builtin/providers/azurerm/resource_arm_subnet_test.go index 5f6314d26078..844e04f99254 100644 --- a/builtin/providers/azurerm/resource_arm_subnet_test.go +++ b/builtin/providers/azurerm/resource_arm_subnet_test.go @@ -1,108 +1,108 @@ 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 TestAccAzureRMSubnet_basic(t *testing.T) { -// -// ri := acctest.RandInt() -// config := fmt.Sprintf(testAccAzureRMSubnet_basic, ri, ri, ri) -// -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// Providers: testAccProviders, -// CheckDestroy: testCheckAzureRMSubnetDestroy, -// Steps: []resource.TestStep{ -// resource.TestStep{ -// Config: config, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMSubnetExists("azurerm_subnet.test"), -// ), -// }, -// }, -// }) -//} -// -//func testCheckAzureRMSubnetExists(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) -// } -// -// name := rs.Primary.Attributes["name"] -// vnetName := rs.Primary.Attributes["virtual_network_name"] -// resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] -// if !hasResourceGroup { -// return fmt.Errorf("Bad: no resource group found in state for subnet: %s", name) -// } -// -// conn := testAccProvider.Meta().(*ArmClient).subnetClient -// -// resp, err := conn.Get(resourceGroup, vnetName, name, "") -// if err != nil { -// return fmt.Errorf("Bad: Get on subnetClient: %s", err) -// } -// -// if resp.StatusCode == http.StatusNotFound { -// return fmt.Errorf("Bad: Subnet %q (resource group: %q) does not exist", name, resourceGroup) -// } -// -// return nil -// } -//} -// -//func testCheckAzureRMSubnetDestroy(s *terraform.State) error { -// conn := testAccProvider.Meta().(*ArmClient).subnetClient -// -// for _, rs := range s.RootModule().Resources { -// if rs.Type != "azurerm_subnet" { -// continue -// } -// -// name := rs.Primary.Attributes["name"] -// vnetName := rs.Primary.Attributes["virtual_network_name"] -// resourceGroup := rs.Primary.Attributes["resource_group_name"] -// -// resp, err := conn.Get(resourceGroup, vnetName, name, "") -// -// if err != nil { -// return nil -// } -// -// if resp.StatusCode != http.StatusNotFound { -// return fmt.Errorf("Subnet still exists:\n%#v", resp.Properties) -// } -// } -// -// return nil -//} -// -//var testAccAzureRMSubnet_basic = ` -//resource "azurerm_resource_group" "test" { -// name = "acctestrg-%d" -// location = "West US" -//} -// -//resource "azurerm_virtual_network" "test" { -// name = "acctestvirtnet%d" -// address_space = ["10.0.0.0/16"] -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -//} -// -//resource "azurerm_subnet" "test" { -// name = "acctestsubnet%d" -// resource_group_name = "${azurerm_resource_group.test.name}" -// virtual_network_name = "${azurerm_virtual_network.test.name}" -// address_prefix = "10.0.2.0/24" -//} -//` +import ( + "fmt" + "net/http" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAzureRMSubnet_basic(t *testing.T) { + + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMSubnet_basic, ri, ri, ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMSubnetDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMSubnetExists("azurerm_subnet.test"), + ), + }, + }, + }) +} + +func testCheckAzureRMSubnetExists(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) + } + + name := rs.Primary.Attributes["name"] + vnetName := rs.Primary.Attributes["virtual_network_name"] + resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] + if !hasResourceGroup { + return fmt.Errorf("Bad: no resource group found in state for subnet: %s", name) + } + + conn := testAccProvider.Meta().(*ArmClient).subnetClient + + resp, err := conn.Get(resourceGroup, vnetName, name, "") + if err != nil { + return fmt.Errorf("Bad: Get on subnetClient: %s", err) + } + + if resp.StatusCode == http.StatusNotFound { + return fmt.Errorf("Bad: Subnet %q (resource group: %q) does not exist", name, resourceGroup) + } + + return nil + } +} + +func testCheckAzureRMSubnetDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*ArmClient).subnetClient + + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_subnet" { + continue + } + + name := rs.Primary.Attributes["name"] + vnetName := rs.Primary.Attributes["virtual_network_name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] + + resp, err := conn.Get(resourceGroup, vnetName, name, "") + + if err != nil { + return nil + } + + if resp.StatusCode != http.StatusNotFound { + return fmt.Errorf("Subnet still exists:\n%#v", resp.Properties) + } + } + + return nil +} + +var testAccAzureRMSubnet_basic = ` +resource "azurerm_resource_group" "test" { + name = "acctestrg-%d" + location = "West US" +} + +resource "azurerm_virtual_network" "test" { + name = "acctestvirtnet%d" + address_space = ["10.0.0.0/16"] + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" +} + +resource "azurerm_subnet" "test" { + name = "acctestsubnet%d" + resource_group_name = "${azurerm_resource_group.test.name}" + virtual_network_name = "${azurerm_virtual_network.test.name}" + address_prefix = "10.0.2.0/24" +} +` From 3831553c72d8c5a7fcb929c69e76354025a86b5f Mon Sep 17 00:00:00 2001 From: James Nugent Date: Wed, 1 Jun 2016 17:18:50 -0500 Subject: [PATCH 05/17] provider/azurerm: Fix azurerm_public_ip ``` HTTP_PROXY=http://localhost:8888 make testacc TEST=./builtin/providers/azurerm TESTARGS="-run TestAccAzureRMPublicIpStatic" ==> Checking that code complies with gofmt requirements... /Users/James/Code/go/bin/stringer go generate $(go list ./... | grep -v /vendor/) 2016/06/01 17:09:54 Generated command/internal_plugin_list.go TF_ACC=1 go test ./builtin/providers/azurerm -v -run TestAccAzureRMPublicIpStatic -timeout 120m === RUN TestAccAzureRMPublicIpStatic_basic --- PASS: TestAccAzureRMPublicIpStatic_basic (101.00s) === RUN TestAccAzureRMPublicIpStatic_withTags --- PASS: TestAccAzureRMPublicIpStatic_withTags (125.13s) === RUN TestAccAzureRMPublicIpStatic_update --- PASS: TestAccAzureRMPublicIpStatic_update (128.66s) PASS ok github.com/hashicorp/terraform/builtin/providers/azurerm 354.802s ``` --- builtin/providers/azurerm/provider.go | 2 +- .../azurerm/resource_arm_public_ip.go | 481 +++++++------- .../azurerm/resource_arm_public_ip_test.go | 628 +++++++++--------- 3 files changed, 547 insertions(+), 564 deletions(-) diff --git a/builtin/providers/azurerm/provider.go b/builtin/providers/azurerm/provider.go index c82bf3991169..4cbc4b4f4ce9 100644 --- a/builtin/providers/azurerm/provider.go +++ b/builtin/providers/azurerm/provider.go @@ -52,7 +52,7 @@ func Provider() terraform.ResourceProvider { //"azurerm_network_interface": resourceArmNetworkInterface(), //"azurerm_network_security_group": resourceArmNetworkSecurityGroup(), //"azurerm_network_security_rule": resourceArmNetworkSecurityRule(), - //"azurerm_public_ip": resourceArmPublicIp(), + "azurerm_public_ip": resourceArmPublicIp(), //"azurerm_route": resourceArmRoute(), //"azurerm_route_table": resourceArmRouteTable(), //"azurerm_storage_account": resourceArmStorageAccount(), diff --git a/builtin/providers/azurerm/resource_arm_public_ip.go b/builtin/providers/azurerm/resource_arm_public_ip.go index c9011e08c1ef..bde231e3d4ec 100644 --- a/builtin/providers/azurerm/resource_arm_public_ip.go +++ b/builtin/providers/azurerm/resource_arm_public_ip.go @@ -1,251 +1,234 @@ package azurerm -//import ( -// "fmt" -// "log" -// "net/http" -// "regexp" -// "strings" -// "time" -// -// "github.com/Azure/azure-sdk-for-go/arm/network" -// "github.com/hashicorp/terraform/helper/resource" -// "github.com/hashicorp/terraform/helper/schema" -//) -// -//func resourceArmPublicIp() *schema.Resource { -// return &schema.Resource{ -// Create: resourceArmPublicIpCreate, -// Read: resourceArmPublicIpRead, -// Update: resourceArmPublicIpCreate, -// Delete: resourceArmPublicIpDelete, -// -// Schema: map[string]*schema.Schema{ -// "name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// }, -// -// "location": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// StateFunc: azureRMNormalizeLocation, -// }, -// -// "resource_group_name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// }, -// -// "public_ip_address_allocation": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ValidateFunc: validatePublicIpAllocation, -// }, -// -// "idle_timeout_in_minutes": &schema.Schema{ -// Type: schema.TypeInt, -// Optional: true, -// ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { -// value := v.(int) -// if value < 4 || value > 30 { -// errors = append(errors, fmt.Errorf( -// "The idle timeout must be between 4 and 30 minutes")) -// } -// return -// }, -// }, -// -// "domain_name_label": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// ValidateFunc: validatePublicIpDomainNameLabel, -// }, -// -// "reverse_fqdn": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// }, -// -// "fqdn": &schema.Schema{ -// Type: schema.TypeString, -// Computed: true, -// }, -// -// "ip_address": &schema.Schema{ -// Type: schema.TypeString, -// Computed: true, -// }, -// -// "tags": tagsSchema(), -// }, -// } -//} -// -//func resourceArmPublicIpCreate(d *schema.ResourceData, meta interface{}) error { -// client := meta.(*ArmClient) -// publicIPClient := client.publicIPClient -// -// log.Printf("[INFO] preparing arguments for Azure ARM Public IP creation.") -// -// name := d.Get("name").(string) -// location := d.Get("location").(string) -// resGroup := d.Get("resource_group_name").(string) -// tags := d.Get("tags").(map[string]interface{}) -// -// properties := network.PublicIPAddressPropertiesFormat{ -// PublicIPAllocationMethod: network.IPAllocationMethod(d.Get("public_ip_address_allocation").(string)), -// } -// -// dnl, hasDnl := d.GetOk("domain_name_label") -// rfqdn, hasRfqdn := d.GetOk("reverse_fqdn") -// -// if hasDnl || hasRfqdn { -// dnsSettings := network.PublicIPAddressDNSSettings{} -// -// if hasRfqdn { -// reverse_fqdn := rfqdn.(string) -// dnsSettings.ReverseFqdn = &reverse_fqdn -// } -// -// if hasDnl { -// domain_name_label := dnl.(string) -// dnsSettings.DomainNameLabel = &domain_name_label -// -// } -// -// properties.DNSSettings = &dnsSettings -// } -// -// if v, ok := d.GetOk("idle_timeout_in_minutes"); ok { -// idle_timeout := v.(int) -// properties.IdleTimeoutInMinutes = &idle_timeout -// } -// -// publicIp := network.PublicIPAddress{ -// Name: &name, -// Location: &location, -// Properties: &properties, -// Tags: expandTags(tags), -// } -// -// resp, err := publicIPClient.CreateOrUpdate(resGroup, name, publicIp) -// if err != nil { -// return err -// } -// -// d.SetId(*resp.ID) -// -// log.Printf("[DEBUG] Waiting for Public IP (%s) to become available", name) -// stateConf := &resource.StateChangeConf{ -// Pending: []string{"Accepted", "Updating"}, -// Target: []string{"Succeeded"}, -// Refresh: publicIPStateRefreshFunc(client, resGroup, name), -// Timeout: 10 * time.Minute, -// } -// if _, err := stateConf.WaitForState(); err != nil { -// return fmt.Errorf("Error waiting for Public IP (%s) to become available: %s", name, err) -// } -// -// return resourceArmPublicIpRead(d, meta) -//} -// -//func resourceArmPublicIpRead(d *schema.ResourceData, meta interface{}) error { -// publicIPClient := meta.(*ArmClient).publicIPClient -// -// id, err := parseAzureResourceID(d.Id()) -// if err != nil { -// return err -// } -// resGroup := id.ResourceGroup -// name := id.Path["publicIPAddresses"] -// -// resp, err := publicIPClient.Get(resGroup, name, "") -// if resp.StatusCode == http.StatusNotFound { -// d.SetId("") -// return nil -// } -// if err != nil { -// return fmt.Errorf("Error making Read request on Azure public ip %s: %s", name, err) -// } -// -// if resp.Properties.DNSSettings != nil && resp.Properties.DNSSettings.Fqdn != nil && *resp.Properties.DNSSettings.Fqdn != "" { -// d.Set("fqdn", resp.Properties.DNSSettings.Fqdn) -// } -// -// if resp.Properties.IPAddress != nil && *resp.Properties.IPAddress != "" { -// d.Set("ip_address", resp.Properties.IPAddress) -// } -// -// flattenAndSetTags(d, resp.Tags) -// -// return nil -//} -// -//func resourceArmPublicIpDelete(d *schema.ResourceData, meta interface{}) error { -// publicIPClient := meta.(*ArmClient).publicIPClient -// -// id, err := parseAzureResourceID(d.Id()) -// if err != nil { -// return err -// } -// resGroup := id.ResourceGroup -// name := id.Path["publicIPAddresses"] -// -// _, err = publicIPClient.Delete(resGroup, name) -// -// return err -//} -// -//func publicIPStateRefreshFunc(client *ArmClient, resourceGroupName string, publicIpName string) resource.StateRefreshFunc { -// return func() (interface{}, string, error) { -// res, err := client.publicIPClient.Get(resourceGroupName, publicIpName, "") -// if err != nil { -// return nil, "", fmt.Errorf("Error issuing read request in publicIPStateRefreshFunc to Azure ARM for public ip '%s' (RG: '%s'): %s", publicIpName, resourceGroupName, err) -// } -// -// return res, *res.Properties.ProvisioningState, nil -// } -//} -// -//func validatePublicIpAllocation(v interface{}, k string) (ws []string, errors []error) { -// value := strings.ToLower(v.(string)) -// allocations := map[string]bool{ -// "static": true, -// "dynamic": true, -// } -// -// if !allocations[value] { -// errors = append(errors, fmt.Errorf("Public IP Allocation can only be Static of Dynamic")) -// } -// return -//} -// -//func validatePublicIpDomainNameLabel(v interface{}, k string) (ws []string, errors []error) { -// value := v.(string) -// if !regexp.MustCompile(`^[a-z0-9-]+$`).MatchString(value) { -// errors = append(errors, fmt.Errorf( -// "only alphanumeric characters and hyphens allowed in %q: %q", -// k, value)) -// } -// -// if len(value) > 61 { -// errors = append(errors, fmt.Errorf( -// "%q cannot be longer than 61 characters: %q", k, value)) -// } -// -// if len(value) == 0 { -// errors = append(errors, fmt.Errorf( -// "%q cannot be an empty string: %q", k, value)) -// } -// if regexp.MustCompile(`-$`).MatchString(value) { -// errors = append(errors, fmt.Errorf( -// "%q cannot end with a hyphen: %q", k, value)) -// } -// -// return -// -//} +import ( + "fmt" + "log" + "net/http" + "regexp" + "strings" + + "github.com/Azure/azure-sdk-for-go/arm/network" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceArmPublicIp() *schema.Resource { + return &schema.Resource{ + Create: resourceArmPublicIpCreate, + Read: resourceArmPublicIpRead, + Update: resourceArmPublicIpCreate, + Delete: resourceArmPublicIpDelete, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "location": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + StateFunc: azureRMNormalizeLocation, + }, + + "resource_group_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "public_ip_address_allocation": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validatePublicIpAllocation, + }, + + "idle_timeout_in_minutes": { + Type: schema.TypeInt, + Optional: true, + ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { + value := v.(int) + if value < 4 || value > 30 { + errors = append(errors, fmt.Errorf( + "The idle timeout must be between 4 and 30 minutes")) + } + return + }, + }, + + "domain_name_label": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validatePublicIpDomainNameLabel, + }, + + "reverse_fqdn": { + Type: schema.TypeString, + Optional: true, + }, + + "fqdn": { + Type: schema.TypeString, + Computed: true, + }, + + "ip_address": { + Type: schema.TypeString, + Computed: true, + }, + + "tags": tagsSchema(), + }, + } +} + +func resourceArmPublicIpCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient) + publicIPClient := client.publicIPClient + + log.Printf("[INFO] preparing arguments for Azure ARM Public IP creation.") + + name := d.Get("name").(string) + location := d.Get("location").(string) + resGroup := d.Get("resource_group_name").(string) + tags := d.Get("tags").(map[string]interface{}) + + properties := network.PublicIPAddressPropertiesFormat{ + PublicIPAllocationMethod: network.IPAllocationMethod(d.Get("public_ip_address_allocation").(string)), + } + + dnl, hasDnl := d.GetOk("domain_name_label") + rfqdn, hasRfqdn := d.GetOk("reverse_fqdn") + + if hasDnl || hasRfqdn { + dnsSettings := network.PublicIPAddressDNSSettings{} + + if hasRfqdn { + reverse_fqdn := rfqdn.(string) + dnsSettings.ReverseFqdn = &reverse_fqdn + } + + if hasDnl { + domain_name_label := dnl.(string) + dnsSettings.DomainNameLabel = &domain_name_label + + } + + properties.DNSSettings = &dnsSettings + } + + if v, ok := d.GetOk("idle_timeout_in_minutes"); ok { + idle_timeout := v.(int32) + properties.IdleTimeoutInMinutes = &idle_timeout + } + + publicIp := network.PublicIPAddress{ + Name: &name, + Location: &location, + Properties: &properties, + Tags: expandTags(tags), + } + + _, err := publicIPClient.CreateOrUpdate(resGroup, name, publicIp, make(chan struct{})) + if err != nil { + return err + } + + read, err := publicIPClient.Get(resGroup, name, "") + if err != nil { + return err + } + if read.ID == nil { + return fmt.Errorf("Cannot read Public IP %s (resource group %s) ID", name, resGroup) + } + + d.SetId(*read.ID) + + return resourceArmPublicIpRead(d, meta) +} + +func resourceArmPublicIpRead(d *schema.ResourceData, meta interface{}) error { + publicIPClient := meta.(*ArmClient).publicIPClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + name := id.Path["publicIPAddresses"] + + resp, err := publicIPClient.Get(resGroup, name, "") + if resp.StatusCode == http.StatusNotFound { + d.SetId("") + return nil + } + if err != nil { + return fmt.Errorf("Error making Read request on Azure public ip %s: %s", name, err) + } + + if resp.Properties.DNSSettings != nil && resp.Properties.DNSSettings.Fqdn != nil && *resp.Properties.DNSSettings.Fqdn != "" { + d.Set("fqdn", resp.Properties.DNSSettings.Fqdn) + } + + if resp.Properties.IPAddress != nil && *resp.Properties.IPAddress != "" { + d.Set("ip_address", resp.Properties.IPAddress) + } + + flattenAndSetTags(d, resp.Tags) + + return nil +} + +func resourceArmPublicIpDelete(d *schema.ResourceData, meta interface{}) error { + publicIPClient := meta.(*ArmClient).publicIPClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + name := id.Path["publicIPAddresses"] + + _, err = publicIPClient.Delete(resGroup, name, make(chan struct{})) + + return err +} + +func validatePublicIpAllocation(v interface{}, k string) (ws []string, errors []error) { + value := strings.ToLower(v.(string)) + allocations := map[string]bool{ + "static": true, + "dynamic": true, + } + + if !allocations[value] { + errors = append(errors, fmt.Errorf("Public IP Allocation can only be Static of Dynamic")) + } + return +} + +func validatePublicIpDomainNameLabel(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + if !regexp.MustCompile(`^[a-z0-9-]+$`).MatchString(value) { + errors = append(errors, fmt.Errorf( + "only alphanumeric characters and hyphens allowed in %q: %q", + k, value)) + } + + if len(value) > 61 { + errors = append(errors, fmt.Errorf( + "%q cannot be longer than 61 characters: %q", k, value)) + } + + if len(value) == 0 { + errors = append(errors, fmt.Errorf( + "%q cannot be an empty string: %q", k, value)) + } + if regexp.MustCompile(`-$`).MatchString(value) { + errors = append(errors, fmt.Errorf( + "%q cannot end with a hyphen: %q", k, value)) + } + + return +} diff --git a/builtin/providers/azurerm/resource_arm_public_ip_test.go b/builtin/providers/azurerm/resource_arm_public_ip_test.go index bd9f08fd7eb6..eaf4a36461dc 100644 --- a/builtin/providers/azurerm/resource_arm_public_ip_test.go +++ b/builtin/providers/azurerm/resource_arm_public_ip_test.go @@ -1,316 +1,316 @@ 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 TestResourceAzureRMPublicIpAllocation_validation(t *testing.T) { -// cases := []struct { -// Value string -// ErrCount int -// }{ -// { -// Value: "Random", -// ErrCount: 1, -// }, -// { -// Value: "Static", -// ErrCount: 0, -// }, -// { -// Value: "Dynamic", -// ErrCount: 0, -// }, -// { -// Value: "STATIC", -// ErrCount: 0, -// }, -// { -// Value: "static", -// ErrCount: 0, -// }, -// } -// -// for _, tc := range cases { -// _, errors := validatePublicIpAllocation(tc.Value, "azurerm_public_ip") -// -// if len(errors) != tc.ErrCount { -// t.Fatalf("Expected the Azure RM Public IP allocation to trigger a validation error") -// } -// } -//} -// -//func TestResourceAzureRMPublicIpDomainNameLabel_validation(t *testing.T) { -// cases := []struct { -// Value string -// ErrCount int -// }{ -// { -// Value: "tEsting123", -// ErrCount: 1, -// }, -// { -// Value: "testing123!", -// ErrCount: 1, -// }, -// { -// Value: "testing123-", -// ErrCount: 1, -// }, -// { -// Value: acctest.RandString(80), -// ErrCount: 1, -// }, -// } -// -// for _, tc := range cases { -// _, errors := validatePublicIpDomainNameLabel(tc.Value, "azurerm_public_ip") -// -// if len(errors) != tc.ErrCount { -// t.Fatalf("Expected the Azure RM Public IP Domain Name Label to trigger a validation error") -// } -// } -//} -// -//func TestAccAzureRMPublicIpStatic_basic(t *testing.T) { -// -// ri := acctest.RandInt() -// config := fmt.Sprintf(testAccAzureRMVPublicIpStatic_basic, ri, ri) -// -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// Providers: testAccProviders, -// CheckDestroy: testCheckAzureRMPublicIpDestroy, -// Steps: []resource.TestStep{ -// resource.TestStep{ -// Config: config, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMPublicIpExists("azurerm_public_ip.test"), -// ), -// }, -// }, -// }) -//} -// -//func TestAccAzureRMPublicIpStatic_withTags(t *testing.T) { -// -// ri := acctest.RandInt() -// preConfig := fmt.Sprintf(testAccAzureRMVPublicIpStatic_withTags, ri, ri) -// postConfig := fmt.Sprintf(testAccAzureRMVPublicIpStatic_withTagsUpdate, ri, ri) -// -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// Providers: testAccProviders, -// CheckDestroy: testCheckAzureRMPublicIpDestroy, -// Steps: []resource.TestStep{ -// resource.TestStep{ -// Config: preConfig, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMPublicIpExists("azurerm_public_ip.test"), -// resource.TestCheckResourceAttr( -// "azurerm_public_ip.test", "tags.#", "2"), -// resource.TestCheckResourceAttr( -// "azurerm_public_ip.test", "tags.environment", "Production"), -// resource.TestCheckResourceAttr( -// "azurerm_public_ip.test", "tags.cost_center", "MSFT"), -// ), -// }, -// -// resource.TestStep{ -// Config: postConfig, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMPublicIpExists("azurerm_public_ip.test"), -// resource.TestCheckResourceAttr( -// "azurerm_public_ip.test", "tags.#", "1"), -// resource.TestCheckResourceAttr( -// "azurerm_public_ip.test", "tags.environment", "staging"), -// ), -// }, -// }, -// }) -//} -// -//func TestAccAzureRMPublicIpStatic_update(t *testing.T) { -// -// ri := acctest.RandInt() -// preConfig := fmt.Sprintf(testAccAzureRMVPublicIpStatic_basic, ri, ri) -// postConfig := fmt.Sprintf(testAccAzureRMVPublicIpStatic_update, ri, ri) -// -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// Providers: testAccProviders, -// CheckDestroy: testCheckAzureRMPublicIpDestroy, -// Steps: []resource.TestStep{ -// resource.TestStep{ -// Config: preConfig, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMPublicIpExists("azurerm_public_ip.test"), -// ), -// }, -// -// resource.TestStep{ -// Config: postConfig, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMPublicIpExists("azurerm_public_ip.test"), -// resource.TestCheckResourceAttr( -// "azurerm_public_ip.test", "domain_name_label", "mylabel01"), -// ), -// }, -// }, -// }) -//} -// -//func TestAccAzureRMPublicIpDynamic_basic(t *testing.T) { -// -// ri := acctest.RandInt() -// config := fmt.Sprintf(testAccAzureRMVPublicIpDynamic_basic, ri, ri) -// -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// Providers: testAccProviders, -// CheckDestroy: testCheckAzureRMPublicIpDestroy, -// Steps: []resource.TestStep{ -// resource.TestStep{ -// Config: config, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMPublicIpExists("azurerm_public_ip.test"), -// ), -// }, -// }, -// }) -//} -// -//func testCheckAzureRMPublicIpExists(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) -// } -// -// availSetName := rs.Primary.Attributes["name"] -// resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] -// if !hasResourceGroup { -// return fmt.Errorf("Bad: no resource group found in state for public ip: %s", availSetName) -// } -// -// conn := testAccProvider.Meta().(*ArmClient).publicIPClient -// -// resp, err := conn.Get(resourceGroup, availSetName, "") -// if err != nil { -// return fmt.Errorf("Bad: Get on publicIPClient: %s", err) -// } -// -// if resp.StatusCode == http.StatusNotFound { -// return fmt.Errorf("Bad: Public IP %q (resource group: %q) does not exist", name, resourceGroup) -// } -// -// return nil -// } -//} -// -//func testCheckAzureRMPublicIpDestroy(s *terraform.State) error { -// conn := testAccProvider.Meta().(*ArmClient).publicIPClient -// -// for _, rs := range s.RootModule().Resources { -// if rs.Type != "azurerm_public_ip" { -// continue -// } -// -// name := rs.Primary.Attributes["name"] -// resourceGroup := rs.Primary.Attributes["resource_group_name"] -// -// resp, err := conn.Get(resourceGroup, name, "") -// -// if err != nil { -// return nil -// } -// -// if resp.StatusCode != http.StatusNotFound { -// return fmt.Errorf("Public IP still exists:\n%#v", resp.Properties) -// } -// } -// -// return nil -//} -// -//var testAccAzureRMVPublicIpStatic_basic = ` -//resource "azurerm_resource_group" "test" { -// name = "acctestrg-%d" -// location = "West US" -//} -//resource "azurerm_public_ip" "test" { -// name = "acctestpublicip-%d" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// public_ip_address_allocation = "static" -//} -//` -// -//var testAccAzureRMVPublicIpStatic_update = ` -//resource "azurerm_resource_group" "test" { -// name = "acctestrg-%d" -// location = "West US" -//} -//resource "azurerm_public_ip" "test" { -// name = "acctestpublicip-%d" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// public_ip_address_allocation = "static" -// domain_name_label = "mylabel01" -//} -//` -// -//var testAccAzureRMVPublicIpDynamic_basic = ` -//resource "azurerm_resource_group" "test" { -// name = "acctestrg-%d" -// location = "West US" -//} -//resource "azurerm_public_ip" "test" { -// name = "acctestpublicip-%d" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// public_ip_address_allocation = "dynamic" -//} -//` -// -//var testAccAzureRMVPublicIpStatic_withTags = ` -//resource "azurerm_resource_group" "test" { -// name = "acctestrg-%d" -// location = "West US" -//} -//resource "azurerm_public_ip" "test" { -// name = "acctestpublicip-%d" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// public_ip_address_allocation = "static" -// -// tags { -// environment = "Production" -// cost_center = "MSFT" -// } -//} -//` -// -//var testAccAzureRMVPublicIpStatic_withTagsUpdate = ` -//resource "azurerm_resource_group" "test" { -// name = "acctestrg-%d" -// location = "West US" -//} -//resource "azurerm_public_ip" "test" { -// name = "acctestpublicip-%d" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// public_ip_address_allocation = "static" -// -// tags { -// environment = "staging" -// } -//} -//` +import ( + "fmt" + "net/http" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestResourceAzureRMPublicIpAllocation_validation(t *testing.T) { + cases := []struct { + Value string + ErrCount int + }{ + { + Value: "Random", + ErrCount: 1, + }, + { + Value: "Static", + ErrCount: 0, + }, + { + Value: "Dynamic", + ErrCount: 0, + }, + { + Value: "STATIC", + ErrCount: 0, + }, + { + Value: "static", + ErrCount: 0, + }, + } + + for _, tc := range cases { + _, errors := validatePublicIpAllocation(tc.Value, "azurerm_public_ip") + + if len(errors) != tc.ErrCount { + t.Fatalf("Expected the Azure RM Public IP allocation to trigger a validation error") + } + } +} + +func TestResourceAzureRMPublicIpDomainNameLabel_validation(t *testing.T) { + cases := []struct { + Value string + ErrCount int + }{ + { + Value: "tEsting123", + ErrCount: 1, + }, + { + Value: "testing123!", + ErrCount: 1, + }, + { + Value: "testing123-", + ErrCount: 1, + }, + { + Value: acctest.RandString(80), + ErrCount: 1, + }, + } + + for _, tc := range cases { + _, errors := validatePublicIpDomainNameLabel(tc.Value, "azurerm_public_ip") + + if len(errors) != tc.ErrCount { + t.Fatalf("Expected the Azure RM Public IP Domain Name Label to trigger a validation error") + } + } +} + +func TestAccAzureRMPublicIpStatic_basic(t *testing.T) { + + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMVPublicIpStatic_basic, ri, ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMPublicIpDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMPublicIpExists("azurerm_public_ip.test"), + ), + }, + }, + }) +} + +func TestAccAzureRMPublicIpStatic_withTags(t *testing.T) { + + ri := acctest.RandInt() + preConfig := fmt.Sprintf(testAccAzureRMVPublicIpStatic_withTags, ri, ri) + postConfig := fmt.Sprintf(testAccAzureRMVPublicIpStatic_withTagsUpdate, ri, ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMPublicIpDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: preConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMPublicIpExists("azurerm_public_ip.test"), + resource.TestCheckResourceAttr( + "azurerm_public_ip.test", "tags.#", "2"), + resource.TestCheckResourceAttr( + "azurerm_public_ip.test", "tags.environment", "Production"), + resource.TestCheckResourceAttr( + "azurerm_public_ip.test", "tags.cost_center", "MSFT"), + ), + }, + + resource.TestStep{ + Config: postConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMPublicIpExists("azurerm_public_ip.test"), + resource.TestCheckResourceAttr( + "azurerm_public_ip.test", "tags.#", "1"), + resource.TestCheckResourceAttr( + "azurerm_public_ip.test", "tags.environment", "staging"), + ), + }, + }, + }) +} + +func TestAccAzureRMPublicIpStatic_update(t *testing.T) { + + ri := acctest.RandInt() + preConfig := fmt.Sprintf(testAccAzureRMVPublicIpStatic_basic, ri, ri) + postConfig := fmt.Sprintf(testAccAzureRMVPublicIpStatic_update, ri, ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMPublicIpDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: preConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMPublicIpExists("azurerm_public_ip.test"), + ), + }, + + resource.TestStep{ + Config: postConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMPublicIpExists("azurerm_public_ip.test"), + resource.TestCheckResourceAttr( + "azurerm_public_ip.test", "domain_name_label", "mylabel01"), + ), + }, + }, + }) +} + +func TestAccAzureRMPublicIpDynamic_basic(t *testing.T) { + + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMVPublicIpDynamic_basic, ri, ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMPublicIpDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMPublicIpExists("azurerm_public_ip.test"), + ), + }, + }, + }) +} + +func testCheckAzureRMPublicIpExists(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) + } + + availSetName := rs.Primary.Attributes["name"] + resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] + if !hasResourceGroup { + return fmt.Errorf("Bad: no resource group found in state for public ip: %s", availSetName) + } + + conn := testAccProvider.Meta().(*ArmClient).publicIPClient + + resp, err := conn.Get(resourceGroup, availSetName, "") + if err != nil { + return fmt.Errorf("Bad: Get on publicIPClient: %s", err) + } + + if resp.StatusCode == http.StatusNotFound { + return fmt.Errorf("Bad: Public IP %q (resource group: %q) does not exist", name, resourceGroup) + } + + return nil + } +} + +func testCheckAzureRMPublicIpDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*ArmClient).publicIPClient + + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_public_ip" { + continue + } + + name := rs.Primary.Attributes["name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] + + resp, err := conn.Get(resourceGroup, name, "") + + if err != nil { + return nil + } + + if resp.StatusCode != http.StatusNotFound { + return fmt.Errorf("Public IP still exists:\n%#v", resp.Properties) + } + } + + return nil +} + +var testAccAzureRMVPublicIpStatic_basic = ` +resource "azurerm_resource_group" "test" { + name = "acctestrg-%d" + location = "West US" +} +resource "azurerm_public_ip" "test" { + name = "acctestpublicip-%d" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + public_ip_address_allocation = "static" +} +` + +var testAccAzureRMVPublicIpStatic_update = ` +resource "azurerm_resource_group" "test" { + name = "acctestrg-%d" + location = "West US" +} +resource "azurerm_public_ip" "test" { + name = "acctestpublicip-%d" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + public_ip_address_allocation = "static" + domain_name_label = "mylabel01" +} +` + +var testAccAzureRMVPublicIpDynamic_basic = ` +resource "azurerm_resource_group" "test" { + name = "acctestrg-%d" + location = "West US" +} +resource "azurerm_public_ip" "test" { + name = "acctestpublicip-%d" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + public_ip_address_allocation = "dynamic" +} +` + +var testAccAzureRMVPublicIpStatic_withTags = ` +resource "azurerm_resource_group" "test" { + name = "acctestrg-%d" + location = "West US" +} +resource "azurerm_public_ip" "test" { + name = "acctestpublicip-%d" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + public_ip_address_allocation = "static" + + tags { + environment = "Production" + cost_center = "MSFT" + } +} +` + +var testAccAzureRMVPublicIpStatic_withTagsUpdate = ` +resource "azurerm_resource_group" "test" { + name = "acctestrg-%d" + location = "West US" +} +resource "azurerm_public_ip" "test" { + name = "acctestpublicip-%d" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + public_ip_address_allocation = "static" + + tags { + environment = "staging" + } +} +` From 26e2c9bec28fb53d5789bc67bdee96aa07b4ccf6 Mon Sep 17 00:00:00 2001 From: James Nugent Date: Wed, 1 Jun 2016 18:08:14 -0500 Subject: [PATCH 06/17] provider/azurerm: Fix azurerm_storage_account ``` HTTP_PROXY=http://localhost:8888 make testacc TEST=./builtin/providers/azurerm TESTARGS="-run TestAccAzureRMStorageAccount" ==> Checking that code complies with gofmt requirements... /Users/James/Code/go/bin/stringer go generate $(go list ./... | grep -v /vendor/) 2016/06/01 18:05:12 Generated command/internal_plugin_list.go TF_ACC=1 go test ./builtin/providers/azurerm -v -run TestAccAzureRMStorageAccount -timeout 120m === RUN TestAccAzureRMStorageAccount_basic --- PASS: TestAccAzureRMStorageAccount_basic (89.48s) PASS ok github.com/hashicorp/terraform/builtin/providers/azurerm 89.491s ``` --- builtin/providers/azurerm/provider.go | 4 +- .../azurerm/resource_arm_storage_account.go | 602 +++++++++--------- .../resource_arm_storage_account_test.go | 328 +++++----- 3 files changed, 461 insertions(+), 473 deletions(-) diff --git a/builtin/providers/azurerm/provider.go b/builtin/providers/azurerm/provider.go index 4cbc4b4f4ce9..de93f31f39d0 100644 --- a/builtin/providers/azurerm/provider.go +++ b/builtin/providers/azurerm/provider.go @@ -55,8 +55,8 @@ func Provider() terraform.ResourceProvider { "azurerm_public_ip": resourceArmPublicIp(), //"azurerm_route": resourceArmRoute(), //"azurerm_route_table": resourceArmRouteTable(), - //"azurerm_storage_account": resourceArmStorageAccount(), - "azurerm_storage_blob": resourceArmStorageBlob(), + "azurerm_storage_account": resourceArmStorageAccount(), + "azurerm_storage_blob": resourceArmStorageBlob(), //"azurerm_storage_container": resourceArmStorageContainer(), "azurerm_storage_queue": resourceArmStorageQueue(), "azurerm_subnet": resourceArmSubnet(), diff --git a/builtin/providers/azurerm/resource_arm_storage_account.go b/builtin/providers/azurerm/resource_arm_storage_account.go index 059e9165eee8..2a075529c8c0 100644 --- a/builtin/providers/azurerm/resource_arm_storage_account.go +++ b/builtin/providers/azurerm/resource_arm_storage_account.go @@ -1,309 +1,297 @@ package azurerm -//import ( -// "fmt" -// "net/http" -// "regexp" -// "strings" -// -// "github.com/Azure/azure-sdk-for-go/arm/storage" -// "github.com/hashicorp/terraform/helper/schema" -//) -// -//func resourceArmStorageAccount() *schema.Resource { -// return &schema.Resource{ -// Create: resourceArmStorageAccountCreate, -// Read: resourceArmStorageAccountRead, -// Update: resourceArmStorageAccountUpdate, -// Delete: resourceArmStorageAccountDelete, -// -// Schema: map[string]*schema.Schema{ -// "name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// ValidateFunc: validateArmStorageAccountName, -// }, -// -// "resource_group_name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// }, -// -// "location": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// StateFunc: azureRMNormalizeLocation, -// }, -// -// "account_type": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ValidateFunc: validateArmStorageAccountType, -// }, -// -// "primary_location": &schema.Schema{ -// Type: schema.TypeString, -// Computed: true, -// }, -// -// "secondary_location": &schema.Schema{ -// Type: schema.TypeString, -// Computed: true, -// }, -// -// "primary_blob_endpoint": &schema.Schema{ -// Type: schema.TypeString, -// Computed: true, -// }, -// -// "secondary_blob_endpoint": &schema.Schema{ -// Type: schema.TypeString, -// Computed: true, -// }, -// -// "primary_queue_endpoint": &schema.Schema{ -// Type: schema.TypeString, -// Computed: true, -// }, -// -// "secondary_queue_endpoint": &schema.Schema{ -// Type: schema.TypeString, -// Computed: true, -// }, -// -// "primary_table_endpoint": &schema.Schema{ -// Type: schema.TypeString, -// Computed: true, -// }, -// -// "secondary_table_endpoint": &schema.Schema{ -// Type: schema.TypeString, -// Computed: true, -// }, -// -// // NOTE: The API does not appear to expose a secondary file endpoint -// "primary_file_endpoint": &schema.Schema{ -// Type: schema.TypeString, -// Computed: true, -// }, -// -// "primary_access_key": &schema.Schema{ -// Type: schema.TypeString, -// Computed: true, -// }, -// -// "secondary_access_key": &schema.Schema{ -// Type: schema.TypeString, -// Computed: true, -// }, -// -// "tags": tagsSchema(), -// }, -// } -//} -// -//func resourceArmStorageAccountCreate(d *schema.ResourceData, meta interface{}) error { -// client := meta.(*ArmClient).storageServiceClient -// -// resourceGroupName := d.Get("resource_group_name").(string) -// storageAccountName := d.Get("name").(string) -// accountType := d.Get("account_type").(string) -// location := d.Get("location").(string) -// tags := d.Get("tags").(map[string]interface{}) -// -// opts := storage.AccountCreateParameters{ -// Location: &location, -// Properties: &storage.AccountPropertiesCreateParameters{ -// AccountType: storage.AccountType(accountType), -// }, -// Tags: expandTags(tags), -// } -// -// accResp, err := client.Create(resourceGroupName, storageAccountName, opts) -// if err != nil { -// return fmt.Errorf("Error creating Azure Storage Account '%s': %s", storageAccountName, err) -// } -// _, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response.Response, http.StatusOK) -// if err != nil { -// return fmt.Errorf("Error creating Azure Storage Account %q: %s", storageAccountName, err) -// } -// -// // The only way to get the ID back apparently is to read the resource again -// account, err := client.GetProperties(resourceGroupName, storageAccountName) -// if err != nil { -// return fmt.Errorf("Error retrieving Azure Storage Account %q: %s", storageAccountName, err) -// } -// -// d.SetId(*account.ID) -// -// return resourceArmStorageAccountRead(d, meta) -//} -// -//// resourceArmStorageAccountUpdate is unusual in the ARM API where most resources have a combined -//// and idempotent operation for CreateOrUpdate. In particular updating all of the parameters -//// available requires a call to Update per parameter... -//func resourceArmStorageAccountUpdate(d *schema.ResourceData, meta interface{}) error { -// client := meta.(*ArmClient).storageServiceClient -// id, err := parseAzureResourceID(d.Id()) -// if err != nil { -// return err -// } -// storageAccountName := id.Path["storageAccounts"] -// resourceGroupName := id.ResourceGroup -// -// d.Partial(true) -// -// if d.HasChange("account_type") { -// accountType := d.Get("account_type").(string) -// -// opts := storage.AccountUpdateParameters{ -// Properties: &storage.AccountPropertiesUpdateParameters{ -// AccountType: storage.AccountType(accountType), -// }, -// } -// accResp, err := client.Update(resourceGroupName, storageAccountName, opts) -// if err != nil { -// return fmt.Errorf("Error updating Azure Storage Account type %q: %s", storageAccountName, err) -// } -// _, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response.Response, http.StatusOK) -// if err != nil { -// return fmt.Errorf("Error updating Azure Storage Account type %q: %s", storageAccountName, err) -// } -// -// d.SetPartial("account_type") -// } -// -// if d.HasChange("tags") { -// tags := d.Get("tags").(map[string]interface{}) -// -// opts := storage.AccountUpdateParameters{ -// Tags: expandTags(tags), -// } -// accResp, err := client.Update(resourceGroupName, storageAccountName, opts) -// if err != nil { -// return fmt.Errorf("Error updating Azure Storage Account tags %q: %s", storageAccountName, err) -// } -// _, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response.Response, http.StatusOK) -// if err != nil { -// return fmt.Errorf("Error updating Azure Storage Account tags %q: %s", storageAccountName, err) -// } -// -// d.SetPartial("tags") -// } -// -// d.Partial(false) -// return nil -//} -// -//func resourceArmStorageAccountRead(d *schema.ResourceData, meta interface{}) error { -// client := meta.(*ArmClient).storageServiceClient -// -// id, err := parseAzureResourceID(d.Id()) -// if err != nil { -// return err -// } -// name := id.Path["storageAccounts"] -// resGroup := id.ResourceGroup -// -// resp, err := client.GetProperties(resGroup, name) -// if err != nil { -// if resp.StatusCode == http.StatusNotFound { -// d.SetId("") -// return nil -// } -// -// return fmt.Errorf("Error reading the state of AzureRM Storage Account %q: %s", name, err) -// } -// -// keys, err := client.ListKeys(resGroup, name) -// if err != nil { -// return err -// } -// -// d.Set("primary_access_key", keys.Key1) -// d.Set("secondary_access_key", keys.Key2) -// d.Set("location", resp.Location) -// d.Set("account_type", resp.Properties.AccountType) -// d.Set("primary_location", resp.Properties.PrimaryLocation) -// d.Set("secondary_location", resp.Properties.SecondaryLocation) -// -// if resp.Properties.PrimaryEndpoints != nil { -// d.Set("primary_blob_endpoint", resp.Properties.PrimaryEndpoints.Blob) -// d.Set("primary_queue_endpoint", resp.Properties.PrimaryEndpoints.Queue) -// d.Set("primary_table_endpoint", resp.Properties.PrimaryEndpoints.Table) -// d.Set("primary_file_endpoint", resp.Properties.PrimaryEndpoints.File) -// } -// -// if resp.Properties.SecondaryEndpoints != nil { -// if resp.Properties.SecondaryEndpoints.Blob != nil { -// d.Set("secondary_blob_endpoint", resp.Properties.SecondaryEndpoints.Blob) -// } else { -// d.Set("secondary_blob_endpoint", "") -// } -// if resp.Properties.SecondaryEndpoints.Queue != nil { -// d.Set("secondary_queue_endpoint", resp.Properties.SecondaryEndpoints.Queue) -// } else { -// d.Set("secondary_queue_endpoint", "") -// } -// if resp.Properties.SecondaryEndpoints.Table != nil { -// d.Set("secondary_table_endpoint", resp.Properties.SecondaryEndpoints.Table) -// } else { -// d.Set("secondary_table_endpoint", "") -// } -// } -// -// flattenAndSetTags(d, resp.Tags) -// -// return nil -//} -// -//func resourceArmStorageAccountDelete(d *schema.ResourceData, meta interface{}) error { -// client := meta.(*ArmClient).storageServiceClient -// -// id, err := parseAzureResourceID(d.Id()) -// if err != nil { -// return err -// } -// name := id.Path["storageAccounts"] -// resGroup := id.ResourceGroup -// -// accResp, err := client.Delete(resGroup, name) -// if err != nil { -// return fmt.Errorf("Error issuing AzureRM delete request for storage account %q: %s", name, err) -// } -// _, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response, http.StatusNotFound) -// if err != nil { -// return fmt.Errorf("Error polling for AzureRM delete request for storage account %q: %s", name, err) -// } -// -// return nil -//} -// -//func validateArmStorageAccountName(v interface{}, k string) (ws []string, es []error) { -// input := v.(string) -// -// if !regexp.MustCompile(`\A([a-z0-9]{3,24})\z`).MatchString(input) { -// es = append(es, fmt.Errorf("name can only consist of lowercase letters and numbers, and must be between 3 and 24 characters long")) -// } -// -// return -//} -// -//func validateArmStorageAccountType(v interface{}, k string) (ws []string, es []error) { -// validAccountTypes := []string{"standard_lrs", "standard_zrs", -// "standard_grs", "standard_ragrs", "premium_lrs"} -// -// input := strings.ToLower(v.(string)) -// -// for _, valid := range validAccountTypes { -// if valid == input { -// return -// } -// } -// -// es = append(es, fmt.Errorf("Invalid storage account type %q", input)) -// return -//} +import ( + "fmt" + "net/http" + "regexp" + "strings" + + "github.com/Azure/azure-sdk-for-go/arm/storage" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceArmStorageAccount() *schema.Resource { + return &schema.Resource{ + Create: resourceArmStorageAccountCreate, + Read: resourceArmStorageAccountRead, + Update: resourceArmStorageAccountUpdate, + Delete: resourceArmStorageAccountDelete, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validateArmStorageAccountName, + }, + + "resource_group_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "location": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + StateFunc: azureRMNormalizeLocation, + }, + + "account_type": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validateArmStorageAccountType, + }, + + "primary_location": { + Type: schema.TypeString, + Computed: true, + }, + + "secondary_location": { + Type: schema.TypeString, + Computed: true, + }, + + "primary_blob_endpoint": { + Type: schema.TypeString, + Computed: true, + }, + + "secondary_blob_endpoint": { + Type: schema.TypeString, + Computed: true, + }, + + "primary_queue_endpoint": { + Type: schema.TypeString, + Computed: true, + }, + + "secondary_queue_endpoint": { + Type: schema.TypeString, + Computed: true, + }, + + "primary_table_endpoint": { + Type: schema.TypeString, + Computed: true, + }, + + "secondary_table_endpoint": { + Type: schema.TypeString, + Computed: true, + }, + + // NOTE: The API does not appear to expose a secondary file endpoint + "primary_file_endpoint": { + Type: schema.TypeString, + Computed: true, + }, + + "primary_access_key": { + Type: schema.TypeString, + Computed: true, + }, + + "secondary_access_key": { + Type: schema.TypeString, + Computed: true, + }, + + "tags": tagsSchema(), + }, + } +} + +func resourceArmStorageAccountCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).storageServiceClient + + resourceGroupName := d.Get("resource_group_name").(string) + storageAccountName := d.Get("name").(string) + accountType := d.Get("account_type").(string) + location := d.Get("location").(string) + tags := d.Get("tags").(map[string]interface{}) + + opts := storage.AccountCreateParameters{ + Location: &location, + Properties: &storage.AccountPropertiesCreateParameters{ + AccountType: storage.AccountType(accountType), + }, + Tags: expandTags(tags), + } + + _, err := client.Create(resourceGroupName, storageAccountName, opts, make(chan struct{})) + if err != nil { + return fmt.Errorf("Error creating Azure Storage Account '%s': %s", storageAccountName, err) + } + + // The only way to get the ID back apparently is to read the resource again + read, err := client.GetProperties(resourceGroupName, storageAccountName) + if err != nil { + return err + } + if read.ID == nil { + return fmt.Errorf("Cannot read Storage Account %s (resource group %s) ID", + storageAccountName, resourceGroupName) + } + + d.SetId(*read.ID) + + return resourceArmStorageAccountRead(d, meta) +} + +// resourceArmStorageAccountUpdate is unusual in the ARM API where most resources have a combined +// and idempotent operation for CreateOrUpdate. In particular updating all of the parameters +// available requires a call to Update per parameter... +func resourceArmStorageAccountUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).storageServiceClient + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + storageAccountName := id.Path["storageAccounts"] + resourceGroupName := id.ResourceGroup + + d.Partial(true) + + if d.HasChange("account_type") { + accountType := d.Get("account_type").(string) + + opts := storage.AccountUpdateParameters{ + Properties: &storage.AccountPropertiesUpdateParameters{ + AccountType: storage.AccountType(accountType), + }, + } + _, err := client.Update(resourceGroupName, storageAccountName, opts) + if err != nil { + return fmt.Errorf("Error updating Azure Storage Account type %q: %s", storageAccountName, err) + } + + d.SetPartial("account_type") + } + + if d.HasChange("tags") { + tags := d.Get("tags").(map[string]interface{}) + + opts := storage.AccountUpdateParameters{ + Tags: expandTags(tags), + } + _, err := client.Update(resourceGroupName, storageAccountName, opts) + if err != nil { + return fmt.Errorf("Error updating Azure Storage Account tags %q: %s", storageAccountName, err) + } + + d.SetPartial("tags") + } + + d.Partial(false) + return nil +} + +func resourceArmStorageAccountRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).storageServiceClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + name := id.Path["storageAccounts"] + resGroup := id.ResourceGroup + + resp, err := client.GetProperties(resGroup, name) + if err != nil { + if resp.StatusCode == http.StatusNotFound { + d.SetId("") + return nil + } + + return fmt.Errorf("Error reading the state of AzureRM Storage Account %q: %s", name, err) + } + + keys, err := client.ListKeys(resGroup, name) + if err != nil { + return err + } + + d.Set("primary_access_key", keys.Key1) + d.Set("secondary_access_key", keys.Key2) + d.Set("location", resp.Location) + d.Set("account_type", resp.Properties.AccountType) + d.Set("primary_location", resp.Properties.PrimaryLocation) + d.Set("secondary_location", resp.Properties.SecondaryLocation) + + if resp.Properties.PrimaryEndpoints != nil { + d.Set("primary_blob_endpoint", resp.Properties.PrimaryEndpoints.Blob) + d.Set("primary_queue_endpoint", resp.Properties.PrimaryEndpoints.Queue) + d.Set("primary_table_endpoint", resp.Properties.PrimaryEndpoints.Table) + d.Set("primary_file_endpoint", resp.Properties.PrimaryEndpoints.File) + } + + if resp.Properties.SecondaryEndpoints != nil { + if resp.Properties.SecondaryEndpoints.Blob != nil { + d.Set("secondary_blob_endpoint", resp.Properties.SecondaryEndpoints.Blob) + } else { + d.Set("secondary_blob_endpoint", "") + } + if resp.Properties.SecondaryEndpoints.Queue != nil { + d.Set("secondary_queue_endpoint", resp.Properties.SecondaryEndpoints.Queue) + } else { + d.Set("secondary_queue_endpoint", "") + } + if resp.Properties.SecondaryEndpoints.Table != nil { + d.Set("secondary_table_endpoint", resp.Properties.SecondaryEndpoints.Table) + } else { + d.Set("secondary_table_endpoint", "") + } + } + + flattenAndSetTags(d, resp.Tags) + + return nil +} + +func resourceArmStorageAccountDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).storageServiceClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + name := id.Path["storageAccounts"] + resGroup := id.ResourceGroup + + _, err = client.Delete(resGroup, name) + if err != nil { + return fmt.Errorf("Error issuing AzureRM delete request for storage account %q: %s", name, err) + } + + return nil +} + +func validateArmStorageAccountName(v interface{}, k string) (ws []string, es []error) { + input := v.(string) + + if !regexp.MustCompile(`\A([a-z0-9]{3,24})\z`).MatchString(input) { + es = append(es, fmt.Errorf("name can only consist of lowercase letters and numbers, and must be between 3 and 24 characters long")) + } + + return +} + +func validateArmStorageAccountType(v interface{}, k string) (ws []string, es []error) { + validAccountTypes := []string{"standard_lrs", "standard_zrs", + "standard_grs", "standard_ragrs", "premium_lrs"} + + input := strings.ToLower(v.(string)) + + for _, valid := range validAccountTypes { + if valid == input { + return + } + } + + es = append(es, fmt.Errorf("Invalid storage account type %q", input)) + return +} diff --git a/builtin/providers/azurerm/resource_arm_storage_account_test.go b/builtin/providers/azurerm/resource_arm_storage_account_test.go index 9bcc694f2860..6cad5a1f5091 100644 --- a/builtin/providers/azurerm/resource_arm_storage_account_test.go +++ b/builtin/providers/azurerm/resource_arm_storage_account_test.go @@ -1,166 +1,166 @@ package azurerm -//import ( -// "fmt" -// "net/http" -// "testing" -// -// "github.com/hashicorp/terraform/helper/resource" -// "github.com/hashicorp/terraform/terraform" -//) -// -//func TestValidateArmStorageAccountType(t *testing.T) { -// testCases := []struct { -// input string -// shouldError bool -// }{ -// {"standard_lrs", false}, -// {"invalid", true}, -// } -// -// for _, test := range testCases { -// _, es := validateArmStorageAccountType(test.input, "account_type") -// -// if test.shouldError && len(es) == 0 { -// t.Fatalf("Expected validating account_type %q to fail", test.input) -// } -// } -//} -// -//func TestValidateArmStorageAccountName(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 := validateArmStorageAccountName(test.input, "name") -// -// if test.shouldError && len(es) == 0 { -// t.Fatalf("Expected validating name %q to fail", test.input) -// } -// } -//} -// -//func TestAccAzureRMStorageAccount_basic(t *testing.T) { -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// Providers: testAccProviders, -// CheckDestroy: testCheckAzureRMStorageAccountDestroy, -// Steps: []resource.TestStep{ -// resource.TestStep{ -// Config: testAccAzureRMStorageAccount_basic, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMStorageAccountExists("azurerm_storage_account.testsa"), -// resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "account_type", "Standard_LRS"), -// resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "tags.#", "1"), -// resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "tags.environment", "production"), -// ), -// }, -// -// resource.TestStep{ -// Config: testAccAzureRMStorageAccount_update, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMStorageAccountExists("azurerm_storage_account.testsa"), -// resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "account_type", "Standard_GRS"), -// resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "tags.#", "1"), -// resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "tags.environment", "staging"), -// ), -// }, -// }, -// }) -//} -// -//func testCheckAzureRMStorageAccountExists(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) -// } -// -// storageAccount := rs.Primary.Attributes["name"] -// resourceGroup := rs.Primary.Attributes["resource_group_name"] -// -// // Ensure resource group exists in API -// conn := testAccProvider.Meta().(*ArmClient).storageServiceClient -// -// resp, err := conn.GetProperties(resourceGroup, storageAccount) -// if err != nil { -// return fmt.Errorf("Bad: Get on storageServiceClient: %s", err) -// } -// -// if resp.StatusCode == http.StatusNotFound { -// return fmt.Errorf("Bad: StorageAccount %q (resource group: %q) does not exist", name, resourceGroup) -// } -// -// return nil -// } -//} -// -//func testCheckAzureRMStorageAccountDestroy(s *terraform.State) error { -// conn := testAccProvider.Meta().(*ArmClient).storageServiceClient -// -// for _, rs := range s.RootModule().Resources { -// if rs.Type != "azurerm_storage_account" { -// continue -// } -// -// name := rs.Primary.Attributes["name"] -// resourceGroup := rs.Primary.Attributes["resource_group_name"] -// -// resp, err := conn.GetProperties(resourceGroup, name) -// if err != nil { -// return nil -// } -// -// if resp.StatusCode != http.StatusNotFound { -// return fmt.Errorf("Storage Account still exists:\n%#v", resp.Properties) -// } -// } -// -// return nil -//} -// -//var testAccAzureRMStorageAccount_basic = ` -//resource "azurerm_resource_group" "testrg" { -// name = "testAccAzureRMStorageAccountBasic" -// location = "westus" -//} -// -//resource "azurerm_storage_account" "testsa" { -// name = "unlikely23exst2acct1435" -// resource_group_name = "${azurerm_resource_group.testrg.name}" -// -// location = "westus" -// account_type = "Standard_LRS" -// -// tags { -// environment = "production" -// } -//}` -// -//var testAccAzureRMStorageAccount_update = ` -//resource "azurerm_resource_group" "testrg" { -// name = "testAccAzureRMStorageAccountBasic" -// location = "westus" -//} -// -//resource "azurerm_storage_account" "testsa" { -// name = "unlikely23exst2acct1435" -// resource_group_name = "${azurerm_resource_group.testrg.name}" -// -// location = "westus" -// account_type = "Standard_GRS" -// -// tags { -// environment = "staging" -// } -//}` +import ( + "fmt" + "net/http" + "testing" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestValidateArmStorageAccountType(t *testing.T) { + testCases := []struct { + input string + shouldError bool + }{ + {"standard_lrs", false}, + {"invalid", true}, + } + + for _, test := range testCases { + _, es := validateArmStorageAccountType(test.input, "account_type") + + if test.shouldError && len(es) == 0 { + t.Fatalf("Expected validating account_type %q to fail", test.input) + } + } +} + +func TestValidateArmStorageAccountName(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 := validateArmStorageAccountName(test.input, "name") + + if test.shouldError && len(es) == 0 { + t.Fatalf("Expected validating name %q to fail", test.input) + } + } +} + +func TestAccAzureRMStorageAccount_basic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMStorageAccountDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccAzureRMStorageAccount_basic, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMStorageAccountExists("azurerm_storage_account.testsa"), + resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "account_type", "Standard_LRS"), + resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "tags.#", "1"), + resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "tags.environment", "production"), + ), + }, + + resource.TestStep{ + Config: testAccAzureRMStorageAccount_update, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMStorageAccountExists("azurerm_storage_account.testsa"), + resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "account_type", "Standard_GRS"), + resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "tags.#", "1"), + resource.TestCheckResourceAttr("azurerm_storage_account.testsa", "tags.environment", "staging"), + ), + }, + }, + }) +} + +func testCheckAzureRMStorageAccountExists(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) + } + + storageAccount := rs.Primary.Attributes["name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] + + // Ensure resource group exists in API + conn := testAccProvider.Meta().(*ArmClient).storageServiceClient + + resp, err := conn.GetProperties(resourceGroup, storageAccount) + if err != nil { + return fmt.Errorf("Bad: Get on storageServiceClient: %s", err) + } + + if resp.StatusCode == http.StatusNotFound { + return fmt.Errorf("Bad: StorageAccount %q (resource group: %q) does not exist", name, resourceGroup) + } + + return nil + } +} + +func testCheckAzureRMStorageAccountDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*ArmClient).storageServiceClient + + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_storage_account" { + continue + } + + name := rs.Primary.Attributes["name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] + + resp, err := conn.GetProperties(resourceGroup, name) + if err != nil { + return nil + } + + if resp.StatusCode != http.StatusNotFound { + return fmt.Errorf("Storage Account still exists:\n%#v", resp.Properties) + } + } + + return nil +} + +var testAccAzureRMStorageAccount_basic = ` +resource "azurerm_resource_group" "testrg" { + name = "testAccAzureRMStorageAccountBasic" + location = "westus" +} + +resource "azurerm_storage_account" "testsa" { + name = "unlikely23exst2acct1435" + resource_group_name = "${azurerm_resource_group.testrg.name}" + + location = "westus" + account_type = "Standard_LRS" + + tags { + environment = "production" + } +}` + +var testAccAzureRMStorageAccount_update = ` +resource "azurerm_resource_group" "testrg" { + name = "testAccAzureRMStorageAccountBasic" + location = "westus" +} + +resource "azurerm_storage_account" "testsa" { + name = "unlikely23exst2acct1435" + resource_group_name = "${azurerm_resource_group.testrg.name}" + + location = "westus" + account_type = "Standard_GRS" + + tags { + environment = "staging" + } +}` From 5f4552179536c78685697253a5e347097337c27a Mon Sep 17 00:00:00 2001 From: James Nugent Date: Wed, 1 Jun 2016 18:14:58 -0500 Subject: [PATCH 07/17] provider/azurerm: Fix azurerm_storage_container ``` HTTP_PROXY=http://localhost:8888 make testacc TEST=./builtin/providers/azurerm TESTARGS="-run TestAccAzureRMStorageContainer" ==> Checking that code complies with gofmt requirements... /Users/James/Code/go/bin/stringer go generate $(go list ./... | grep -v /vendor/) 2016/06/01 18:10:56 Generated command/internal_plugin_list.go TF_ACC=1 go test ./builtin/providers/azurerm -v -run TestAccAzureRMStorageContainer -timeout 120m === RUN TestAccAzureRMStorageContainer_basic --- PASS: TestAccAzureRMStorageContainer_basic (102.16s) === RUN TestAccAzureRMStorageContainer_disappears --- PASS: TestAccAzureRMStorageContainer_disappears (101.05s) PASS ok github.com/hashicorp/terraform/builtin/providers/azurerm 203.221s ``` --- builtin/providers/azurerm/provider.go | 10 +- .../azurerm/resource_arm_storage_container.go | 450 ++++++++--------- .../resource_arm_storage_container_test.go | 478 +++++++++--------- 3 files changed, 469 insertions(+), 469 deletions(-) diff --git a/builtin/providers/azurerm/provider.go b/builtin/providers/azurerm/provider.go index de93f31f39d0..612b91731366 100644 --- a/builtin/providers/azurerm/provider.go +++ b/builtin/providers/azurerm/provider.go @@ -55,11 +55,11 @@ func Provider() terraform.ResourceProvider { "azurerm_public_ip": resourceArmPublicIp(), //"azurerm_route": resourceArmRoute(), //"azurerm_route_table": resourceArmRouteTable(), - "azurerm_storage_account": resourceArmStorageAccount(), - "azurerm_storage_blob": resourceArmStorageBlob(), - //"azurerm_storage_container": resourceArmStorageContainer(), - "azurerm_storage_queue": resourceArmStorageQueue(), - "azurerm_subnet": resourceArmSubnet(), + "azurerm_storage_account": resourceArmStorageAccount(), + "azurerm_storage_blob": resourceArmStorageBlob(), + "azurerm_storage_container": resourceArmStorageContainer(), + "azurerm_storage_queue": resourceArmStorageQueue(), + "azurerm_subnet": resourceArmSubnet(), //"azurerm_template_deployment": resourceArmTemplateDeployment(), //"azurerm_virtual_machine": resourceArmVirtualMachine(), "azurerm_virtual_network": resourceArmVirtualNetwork(), diff --git a/builtin/providers/azurerm/resource_arm_storage_container.go b/builtin/providers/azurerm/resource_arm_storage_container.go index 1b3c3bd9b29f..afdcd263cdf2 100644 --- a/builtin/providers/azurerm/resource_arm_storage_container.go +++ b/builtin/providers/azurerm/resource_arm_storage_container.go @@ -1,227 +1,227 @@ package azurerm -//import ( -// "fmt" -// "log" -// "strings" -// -// "regexp" -// -// "github.com/Azure/azure-sdk-for-go/storage" -// "github.com/hashicorp/terraform/helper/schema" -//) -// -//func resourceArmStorageContainer() *schema.Resource { -// return &schema.Resource{ -// Create: resourceArmStorageContainerCreate, -// Read: resourceArmStorageContainerRead, -// Exists: resourceArmStorageContainerExists, -// Delete: resourceArmStorageContainerDelete, -// -// Schema: map[string]*schema.Schema{ -// "name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// ValidateFunc: validateArmStorageContainerName, -// }, -// "resource_group_name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// }, -// "storage_account_name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// }, -// "container_access_type": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// ForceNew: true, -// Default: "private", -// ValidateFunc: validateArmStorageContainerAccessType, -// }, -// "properties": &schema.Schema{ -// Type: schema.TypeMap, -// Computed: true, -// }, -// }, -// } -//} -// -////Following the naming convention as laid out in the docs -//func validateArmStorageContainerName(v interface{}, k string) (ws []string, errors []error) { -// value := v.(string) -// if !regexp.MustCompile(`^[0-9a-z-]+$`).MatchString(value) { -// errors = append(errors, fmt.Errorf( -// "only lowercase alphanumeric characters and hyphens allowed in %q: %q", -// k, value)) -// } -// if len(value) < 3 || len(value) > 63 { -// errors = append(errors, fmt.Errorf( -// "%q must be between 3 and 63 characters: %q", k, value)) -// } -// if regexp.MustCompile(`^-`).MatchString(value) { -// errors = append(errors, fmt.Errorf( -// "%q cannot begin with a hyphen: %q", k, value)) -// } -// return -//} -// -//func validateArmStorageContainerAccessType(v interface{}, k string) (ws []string, errors []error) { -// value := strings.ToLower(v.(string)) -// validTypes := map[string]struct{}{ -// "private": struct{}{}, -// "blob": struct{}{}, -// "container": struct{}{}, -// } -// -// if _, ok := validTypes[value]; !ok { -// errors = append(errors, fmt.Errorf("Storage container access type %q is invalid, must be %q, %q or %q", value, "private", "blob", "page")) -// } -// return -//} -// -//func resourceArmStorageContainerCreate(d *schema.ResourceData, meta interface{}) error { -// armClient := meta.(*ArmClient) -// -// resourceGroupName := d.Get("resource_group_name").(string) -// storageAccountName := d.Get("storage_account_name").(string) -// -// blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroupName, storageAccountName) -// if err != nil { -// return err -// } -// if !accountExists { -// return fmt.Errorf("Storage Account %q Not Found", storageAccountName) -// } -// -// name := d.Get("name").(string) -// -// var accessType storage.ContainerAccessType -// if d.Get("container_access_type").(string) == "private" { -// accessType = storage.ContainerAccessType("") -// } else { -// accessType = storage.ContainerAccessType(d.Get("container_access_type").(string)) -// } -// -// log.Printf("[INFO] Creating container %q in storage account %q.", name, storageAccountName) -// _, err = blobClient.CreateContainerIfNotExists(name, accessType) -// if err != nil { -// return fmt.Errorf("Error creating container %q in storage account %q: %s", name, storageAccountName, err) -// } -// -// d.SetId(name) -// return resourceArmStorageContainerRead(d, meta) -//} -// -//// resourceAzureStorageContainerRead does all the necessary API calls to -//// read the status of the storage container off Azure. -//func resourceArmStorageContainerRead(d *schema.ResourceData, meta interface{}) error { -// armClient := meta.(*ArmClient) -// -// resourceGroupName := d.Get("resource_group_name").(string) -// storageAccountName := d.Get("storage_account_name").(string) -// -// blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroupName, storageAccountName) -// if err != nil { -// return err -// } -// if !accountExists { -// log.Printf("[DEBUG] Storage account %q not found, removing container %q from state", storageAccountName, d.Id()) -// d.SetId("") -// return nil -// } -// -// name := d.Get("name").(string) -// containers, err := blobClient.ListContainers(storage.ListContainersParameters{ -// Prefix: name, -// Timeout: 90, -// }) -// if err != nil { -// return fmt.Errorf("Failed to retrieve storage containers in account %q: %s", name, err) -// } -// -// var found bool -// for _, cont := range containers.Containers { -// if cont.Name == name { -// found = true -// -// props := make(map[string]interface{}) -// props["last_modified"] = cont.Properties.LastModified -// props["lease_status"] = cont.Properties.LeaseStatus -// props["lease_state"] = cont.Properties.LeaseState -// props["lease_duration"] = cont.Properties.LeaseDuration -// -// d.Set("properties", props) -// } -// } -// -// if !found { -// log.Printf("[INFO] Storage container %q does not exist in account %q, removing from state...", name, storageAccountName) -// d.SetId("") -// } -// -// return nil -//} -// -//func resourceArmStorageContainerExists(d *schema.ResourceData, meta interface{}) (bool, error) { -// armClient := meta.(*ArmClient) -// -// resourceGroupName := d.Get("resource_group_name").(string) -// storageAccountName := d.Get("storage_account_name").(string) -// -// blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroupName, storageAccountName) -// if err != nil { -// return false, err -// } -// if !accountExists { -// log.Printf("[DEBUG] Storage account %q not found, removing container %q from state", storageAccountName, d.Id()) -// d.SetId("") -// return false, nil -// } -// -// name := d.Get("name").(string) -// -// log.Printf("[INFO] Checking existence of storage container %q in storage account %q", name, storageAccountName) -// exists, err := blobClient.ContainerExists(name) -// if err != nil { -// return false, fmt.Errorf("Error querying existence of storage container %q in storage account %q: %s", name, storageAccountName, err) -// } -// -// if !exists { -// log.Printf("[INFO] Storage container %q does not exist in account %q, removing from state...", name, storageAccountName) -// d.SetId("") -// } -// -// return exists, nil -//} -// -//// resourceAzureStorageContainerDelete does all the necessary API calls to -//// delete a storage container off Azure. -//func resourceArmStorageContainerDelete(d *schema.ResourceData, meta interface{}) error { -// armClient := meta.(*ArmClient) -// -// resourceGroupName := d.Get("resource_group_name").(string) -// storageAccountName := d.Get("storage_account_name").(string) -// -// blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroupName, storageAccountName) -// if err != nil { -// return err -// } -// if !accountExists { -// log.Printf("[INFO]Storage Account %q doesn't exist so the container won't exist", storageAccountName) -// return nil -// } -// -// name := d.Get("name").(string) -// -// log.Printf("[INFO] Deleting storage container %q in account %q", name, storageAccountName) -// if _, err := blobClient.DeleteContainerIfExists(name); err != nil { -// return fmt.Errorf("Error deleting storage container %q from storage account %q: %s", name, storageAccountName, err) -// } -// -// d.SetId("") -// return nil -//} +import ( + "fmt" + "log" + "strings" + + "regexp" + + "github.com/Azure/azure-sdk-for-go/storage" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceArmStorageContainer() *schema.Resource { + return &schema.Resource{ + Create: resourceArmStorageContainerCreate, + Read: resourceArmStorageContainerRead, + Exists: resourceArmStorageContainerExists, + Delete: resourceArmStorageContainerDelete, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validateArmStorageContainerName, + }, + "resource_group_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "storage_account_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "container_access_type": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Default: "private", + ValidateFunc: validateArmStorageContainerAccessType, + }, + "properties": { + Type: schema.TypeMap, + Computed: true, + }, + }, + } +} + +//Following the naming convention as laid out in the docs +func validateArmStorageContainerName(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + if !regexp.MustCompile(`^[0-9a-z-]+$`).MatchString(value) { + errors = append(errors, fmt.Errorf( + "only lowercase alphanumeric characters and hyphens allowed in %q: %q", + k, value)) + } + if len(value) < 3 || len(value) > 63 { + errors = append(errors, fmt.Errorf( + "%q must be between 3 and 63 characters: %q", k, value)) + } + if regexp.MustCompile(`^-`).MatchString(value) { + errors = append(errors, fmt.Errorf( + "%q cannot begin with a hyphen: %q", k, value)) + } + return +} + +func validateArmStorageContainerAccessType(v interface{}, k string) (ws []string, errors []error) { + value := strings.ToLower(v.(string)) + validTypes := map[string]struct{}{ + "private": struct{}{}, + "blob": struct{}{}, + "container": struct{}{}, + } + + if _, ok := validTypes[value]; !ok { + errors = append(errors, fmt.Errorf("Storage container access type %q is invalid, must be %q, %q or %q", value, "private", "blob", "page")) + } + return +} + +func resourceArmStorageContainerCreate(d *schema.ResourceData, meta interface{}) error { + armClient := meta.(*ArmClient) + + resourceGroupName := d.Get("resource_group_name").(string) + storageAccountName := d.Get("storage_account_name").(string) + + blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroupName, storageAccountName) + if err != nil { + return err + } + if !accountExists { + return fmt.Errorf("Storage Account %q Not Found", storageAccountName) + } + + name := d.Get("name").(string) + + var accessType storage.ContainerAccessType + if d.Get("container_access_type").(string) == "private" { + accessType = storage.ContainerAccessType("") + } else { + accessType = storage.ContainerAccessType(d.Get("container_access_type").(string)) + } + + log.Printf("[INFO] Creating container %q in storage account %q.", name, storageAccountName) + _, err = blobClient.CreateContainerIfNotExists(name, accessType) + if err != nil { + return fmt.Errorf("Error creating container %q in storage account %q: %s", name, storageAccountName, err) + } + + d.SetId(name) + return resourceArmStorageContainerRead(d, meta) +} + +// resourceAzureStorageContainerRead does all the necessary API calls to +// read the status of the storage container off Azure. +func resourceArmStorageContainerRead(d *schema.ResourceData, meta interface{}) error { + armClient := meta.(*ArmClient) + + resourceGroupName := d.Get("resource_group_name").(string) + storageAccountName := d.Get("storage_account_name").(string) + + blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroupName, storageAccountName) + if err != nil { + return err + } + if !accountExists { + log.Printf("[DEBUG] Storage account %q not found, removing container %q from state", storageAccountName, d.Id()) + d.SetId("") + return nil + } + + name := d.Get("name").(string) + containers, err := blobClient.ListContainers(storage.ListContainersParameters{ + Prefix: name, + Timeout: 90, + }) + if err != nil { + return fmt.Errorf("Failed to retrieve storage containers in account %q: %s", name, err) + } + + var found bool + for _, cont := range containers.Containers { + if cont.Name == name { + found = true + + props := make(map[string]interface{}) + props["last_modified"] = cont.Properties.LastModified + props["lease_status"] = cont.Properties.LeaseStatus + props["lease_state"] = cont.Properties.LeaseState + props["lease_duration"] = cont.Properties.LeaseDuration + + d.Set("properties", props) + } + } + + if !found { + log.Printf("[INFO] Storage container %q does not exist in account %q, removing from state...", name, storageAccountName) + d.SetId("") + } + + return nil +} + +func resourceArmStorageContainerExists(d *schema.ResourceData, meta interface{}) (bool, error) { + armClient := meta.(*ArmClient) + + resourceGroupName := d.Get("resource_group_name").(string) + storageAccountName := d.Get("storage_account_name").(string) + + blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroupName, storageAccountName) + if err != nil { + return false, err + } + if !accountExists { + log.Printf("[DEBUG] Storage account %q not found, removing container %q from state", storageAccountName, d.Id()) + d.SetId("") + return false, nil + } + + name := d.Get("name").(string) + + log.Printf("[INFO] Checking existence of storage container %q in storage account %q", name, storageAccountName) + exists, err := blobClient.ContainerExists(name) + if err != nil { + return false, fmt.Errorf("Error querying existence of storage container %q in storage account %q: %s", name, storageAccountName, err) + } + + if !exists { + log.Printf("[INFO] Storage container %q does not exist in account %q, removing from state...", name, storageAccountName) + d.SetId("") + } + + return exists, nil +} + +// resourceAzureStorageContainerDelete does all the necessary API calls to +// delete a storage container off Azure. +func resourceArmStorageContainerDelete(d *schema.ResourceData, meta interface{}) error { + armClient := meta.(*ArmClient) + + resourceGroupName := d.Get("resource_group_name").(string) + storageAccountName := d.Get("storage_account_name").(string) + + blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroupName, storageAccountName) + if err != nil { + return err + } + if !accountExists { + log.Printf("[INFO]Storage Account %q doesn't exist so the container won't exist", storageAccountName) + return nil + } + + name := d.Get("name").(string) + + log.Printf("[INFO] Deleting storage container %q in account %q", name, storageAccountName) + if _, err := blobClient.DeleteContainerIfExists(name); err != nil { + return fmt.Errorf("Error deleting storage container %q from storage account %q: %s", name, storageAccountName, err) + } + + d.SetId("") + return nil +} diff --git a/builtin/providers/azurerm/resource_arm_storage_container_test.go b/builtin/providers/azurerm/resource_arm_storage_container_test.go index 17e29a258cf5..ee92b14bdd7b 100644 --- a/builtin/providers/azurerm/resource_arm_storage_container_test.go +++ b/builtin/providers/azurerm/resource_arm_storage_container_test.go @@ -1,241 +1,241 @@ package azurerm -//import ( -// "fmt" -// "log" -// "strings" -// "testing" -// -// "github.com/Azure/azure-sdk-for-go/storage" -// "github.com/hashicorp/terraform/helper/acctest" -// "github.com/hashicorp/terraform/helper/resource" -// "github.com/hashicorp/terraform/terraform" -//) -// -//func TestAccAzureRMStorageContainer_basic(t *testing.T) { -// var c storage.Container -// -// ri := acctest.RandInt() -// rs := strings.ToLower(acctest.RandString(11)) -// config := fmt.Sprintf(testAccAzureRMStorageContainer_basic, ri, rs) -// -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// Providers: testAccProviders, -// CheckDestroy: testCheckAzureRMStorageContainerDestroy, -// Steps: []resource.TestStep{ -// resource.TestStep{ -// Config: config, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMStorageContainerExists("azurerm_storage_container.test", &c), -// ), -// }, -// }, -// }) -//} -// -//func TestAccAzureRMStorageContainer_disappears(t *testing.T) { -// var c storage.Container -// -// ri := acctest.RandInt() -// rs := strings.ToLower(acctest.RandString(11)) -// config := fmt.Sprintf(testAccAzureRMStorageContainer_basic, ri, rs) -// -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// Providers: testAccProviders, -// CheckDestroy: testCheckAzureRMStorageContainerDestroy, -// Steps: []resource.TestStep{ -// resource.TestStep{ -// Config: config, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMStorageContainerExists("azurerm_storage_container.test", &c), -// testAccARMStorageContainerDisappears("azurerm_storage_container.test", &c), -// ), -// ExpectNonEmptyPlan: true, -// }, -// }, -// }) -//} -// -//func testCheckAzureRMStorageContainerExists(name string, c *storage.Container) resource.TestCheckFunc { -// return func(s *terraform.State) error { -// -// rs, ok := s.RootModule().Resources[name] -// if !ok { -// return fmt.Errorf("Not found: %s", name) -// } -// -// name := rs.Primary.Attributes["name"] -// storageAccountName := rs.Primary.Attributes["storage_account_name"] -// resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] -// if !hasResourceGroup { -// return fmt.Errorf("Bad: no resource group found in state for storage container: %s", name) -// } -// -// armClient := testAccProvider.Meta().(*ArmClient) -// blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroup, storageAccountName) -// if err != nil { -// return err -// } -// if !accountExists { -// return fmt.Errorf("Bad: Storage Account %q does not exist", storageAccountName) -// } -// -// containers, err := blobClient.ListContainers(storage.ListContainersParameters{ -// Prefix: name, -// Timeout: 90, -// }) -// -// if len(containers.Containers) == 0 { -// return fmt.Errorf("Bad: Storage Container %q (storage account: %q) does not exist", name, storageAccountName) -// } -// -// var found bool -// for _, container := range containers.Containers { -// if container.Name == name { -// found = true -// *c = container -// } -// } -// -// if !found { -// return fmt.Errorf("Bad: Storage Container %q (storage account: %q) does not exist", name, storageAccountName) -// } -// -// return nil -// } -//} -// -//func testAccARMStorageContainerDisappears(name string, c *storage.Container) resource.TestCheckFunc { -// return func(s *terraform.State) error { -// rs, ok := s.RootModule().Resources[name] -// if !ok { -// return fmt.Errorf("Not found: %s", name) -// } -// -// armClient := testAccProvider.Meta().(*ArmClient) -// -// storageAccountName := rs.Primary.Attributes["storage_account_name"] -// resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] -// if !hasResourceGroup { -// return fmt.Errorf("Bad: no resource group found in state for storage container: %s", c.Name) -// } -// -// blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroup, storageAccountName) -// if err != nil { -// return err -// } -// if !accountExists { -// log.Printf("[INFO]Storage Account %q doesn't exist so the container won't exist", storageAccountName) -// return nil -// } -// -// _, err = blobClient.DeleteContainerIfExists(c.Name) -// if err != nil { -// return err -// } -// -// return nil -// } -//} -// -//func testCheckAzureRMStorageContainerDestroy(s *terraform.State) error { -// for _, rs := range s.RootModule().Resources { -// if rs.Type != "azurerm_storage_container" { -// continue -// } -// -// name := rs.Primary.Attributes["name"] -// storageAccountName := rs.Primary.Attributes["storage_account_name"] -// resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] -// if !hasResourceGroup { -// return fmt.Errorf("Bad: no resource group found in state for storage container: %s", name) -// } -// -// armClient := testAccProvider.Meta().(*ArmClient) -// blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroup, storageAccountName) -// if err != nil { -// //If we can't get keys then the blob can't exist -// return nil -// } -// if !accountExists { -// return nil -// } -// -// containers, err := blobClient.ListContainers(storage.ListContainersParameters{ -// Prefix: name, -// Timeout: 90, -// }) -// -// if err != nil { -// return nil -// } -// -// var found bool -// for _, container := range containers.Containers { -// if container.Name == name { -// found = true -// } -// } -// -// if found { -// return fmt.Errorf("Bad: Storage Container %q (storage account: %q) still exist", name, storageAccountName) -// } -// } -// -// return nil -//} -// -//func TestValidateArmStorageContainerName(t *testing.T) { -// validNames := []string{ -// "valid-name", -// "valid02-name", -// } -// for _, v := range validNames { -// _, errors := validateArmStorageContainerName(v, "name") -// if len(errors) != 0 { -// t.Fatalf("%q should be a valid Storage Container Name: %q", v, errors) -// } -// } -// -// invalidNames := []string{ -// "InvalidName1", -// "-invalidname1", -// "invalid_name", -// "invalid!", -// "ww", -// strings.Repeat("w", 65), -// } -// for _, v := range invalidNames { -// _, errors := validateArmStorageContainerName(v, "name") -// if len(errors) == 0 { -// t.Fatalf("%q should be an invalid Storage Container Name", v) -// } -// } -//} -// -//var testAccAzureRMStorageContainer_basic = ` -//resource "azurerm_resource_group" "test" { -// name = "acctestrg-%d" -// location = "westus" -//} -// -//resource "azurerm_storage_account" "test" { -// name = "acctestacc%s" -// resource_group_name = "${azurerm_resource_group.test.name}" -// location = "westus" -// account_type = "Standard_LRS" -// -// tags { -// environment = "staging" -// } -//} -// -//resource "azurerm_storage_container" "test" { -// name = "vhds" -// resource_group_name = "${azurerm_resource_group.test.name}" -// storage_account_name = "${azurerm_storage_account.test.name}" -// container_access_type = "private" -//} -//` +import ( + "fmt" + "log" + "strings" + "testing" + + "github.com/Azure/azure-sdk-for-go/storage" + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAzureRMStorageContainer_basic(t *testing.T) { + var c storage.Container + + ri := acctest.RandInt() + rs := strings.ToLower(acctest.RandString(11)) + config := fmt.Sprintf(testAccAzureRMStorageContainer_basic, ri, rs) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMStorageContainerDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMStorageContainerExists("azurerm_storage_container.test", &c), + ), + }, + }, + }) +} + +func TestAccAzureRMStorageContainer_disappears(t *testing.T) { + var c storage.Container + + ri := acctest.RandInt() + rs := strings.ToLower(acctest.RandString(11)) + config := fmt.Sprintf(testAccAzureRMStorageContainer_basic, ri, rs) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMStorageContainerDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMStorageContainerExists("azurerm_storage_container.test", &c), + testAccARMStorageContainerDisappears("azurerm_storage_container.test", &c), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testCheckAzureRMStorageContainerExists(name string, c *storage.Container) resource.TestCheckFunc { + return func(s *terraform.State) error { + + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + name := rs.Primary.Attributes["name"] + storageAccountName := rs.Primary.Attributes["storage_account_name"] + resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] + if !hasResourceGroup { + return fmt.Errorf("Bad: no resource group found in state for storage container: %s", name) + } + + armClient := testAccProvider.Meta().(*ArmClient) + blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroup, storageAccountName) + if err != nil { + return err + } + if !accountExists { + return fmt.Errorf("Bad: Storage Account %q does not exist", storageAccountName) + } + + containers, err := blobClient.ListContainers(storage.ListContainersParameters{ + Prefix: name, + Timeout: 90, + }) + + if len(containers.Containers) == 0 { + return fmt.Errorf("Bad: Storage Container %q (storage account: %q) does not exist", name, storageAccountName) + } + + var found bool + for _, container := range containers.Containers { + if container.Name == name { + found = true + *c = container + } + } + + if !found { + return fmt.Errorf("Bad: Storage Container %q (storage account: %q) does not exist", name, storageAccountName) + } + + return nil + } +} + +func testAccARMStorageContainerDisappears(name string, c *storage.Container) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + armClient := testAccProvider.Meta().(*ArmClient) + + storageAccountName := rs.Primary.Attributes["storage_account_name"] + resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] + if !hasResourceGroup { + return fmt.Errorf("Bad: no resource group found in state for storage container: %s", c.Name) + } + + blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroup, storageAccountName) + if err != nil { + return err + } + if !accountExists { + log.Printf("[INFO]Storage Account %q doesn't exist so the container won't exist", storageAccountName) + return nil + } + + _, err = blobClient.DeleteContainerIfExists(c.Name) + if err != nil { + return err + } + + return nil + } +} + +func testCheckAzureRMStorageContainerDestroy(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_storage_container" { + continue + } + + name := rs.Primary.Attributes["name"] + storageAccountName := rs.Primary.Attributes["storage_account_name"] + resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] + if !hasResourceGroup { + return fmt.Errorf("Bad: no resource group found in state for storage container: %s", name) + } + + armClient := testAccProvider.Meta().(*ArmClient) + blobClient, accountExists, err := armClient.getBlobStorageClientForStorageAccount(resourceGroup, storageAccountName) + if err != nil { + //If we can't get keys then the blob can't exist + return nil + } + if !accountExists { + return nil + } + + containers, err := blobClient.ListContainers(storage.ListContainersParameters{ + Prefix: name, + Timeout: 90, + }) + + if err != nil { + return nil + } + + var found bool + for _, container := range containers.Containers { + if container.Name == name { + found = true + } + } + + if found { + return fmt.Errorf("Bad: Storage Container %q (storage account: %q) still exist", name, storageAccountName) + } + } + + return nil +} + +func TestValidateArmStorageContainerName(t *testing.T) { + validNames := []string{ + "valid-name", + "valid02-name", + } + for _, v := range validNames { + _, errors := validateArmStorageContainerName(v, "name") + if len(errors) != 0 { + t.Fatalf("%q should be a valid Storage Container Name: %q", v, errors) + } + } + + invalidNames := []string{ + "InvalidName1", + "-invalidname1", + "invalid_name", + "invalid!", + "ww", + strings.Repeat("w", 65), + } + for _, v := range invalidNames { + _, errors := validateArmStorageContainerName(v, "name") + if len(errors) == 0 { + t.Fatalf("%q should be an invalid Storage Container Name", v) + } + } +} + +var testAccAzureRMStorageContainer_basic = ` +resource "azurerm_resource_group" "test" { + name = "acctestrg-%d" + location = "westus" +} + +resource "azurerm_storage_account" "test" { + name = "acctestacc%s" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "westus" + account_type = "Standard_LRS" + + tags { + environment = "staging" + } +} + +resource "azurerm_storage_container" "test" { + name = "vhds" + resource_group_name = "${azurerm_resource_group.test.name}" + storage_account_name = "${azurerm_storage_account.test.name}" + container_access_type = "private" +} +` From 9b9ec7bb6c10c586b73d19d465cc9b4f25d00977 Mon Sep 17 00:00:00 2001 From: James Nugent Date: Wed, 1 Jun 2016 18:24:40 -0500 Subject: [PATCH 08/17] provider/azurerm: Fix azurerm_route_table ``` HTTP_PROXY=http://localhost:8888 make testacc TEST=./builtin/providers/azurerm TESTARGS="-run TestAccAzureRMRouteTable" ==> Checking that code complies with gofmt requirements... /Users/James/Code/go/bin/stringer go generate $(go list ./... | grep -v /vendor/) 2016/06/01 18:19:00 Generated command/internal_plugin_list.go TF_ACC=1 go test ./builtin/providers/azurerm -v -run TestAccAzureRMRouteTable -timeout 120m === RUN TestAccAzureRMRouteTable_basic --- PASS: TestAccAzureRMRouteTable_basic (76.52s) === RUN TestAccAzureRMRouteTable_withTags --- PASS: TestAccAzureRMRouteTable_withTags (92.15s) === RUN TestAccAzureRMRouteTable_multipleRoutes --- PASS: TestAccAzureRMRouteTable_multipleRoutes (98.14s) PASS ok github.com/hashicorp/terraform/builtin/providers/azurerm 266.828s ``` --- builtin/providers/azurerm/provider.go | 2 +- .../azurerm/resource_arm_route_table.go | 496 +++++++-------- .../azurerm/resource_arm_route_table_test.go | 584 +++++++++--------- 3 files changed, 533 insertions(+), 549 deletions(-) diff --git a/builtin/providers/azurerm/provider.go b/builtin/providers/azurerm/provider.go index 612b91731366..08788eef5f79 100644 --- a/builtin/providers/azurerm/provider.go +++ b/builtin/providers/azurerm/provider.go @@ -54,7 +54,7 @@ func Provider() terraform.ResourceProvider { //"azurerm_network_security_rule": resourceArmNetworkSecurityRule(), "azurerm_public_ip": resourceArmPublicIp(), //"azurerm_route": resourceArmRoute(), - //"azurerm_route_table": resourceArmRouteTable(), + "azurerm_route_table": resourceArmRouteTable(), "azurerm_storage_account": resourceArmStorageAccount(), "azurerm_storage_blob": resourceArmStorageBlob(), "azurerm_storage_container": resourceArmStorageContainer(), diff --git a/builtin/providers/azurerm/resource_arm_route_table.go b/builtin/providers/azurerm/resource_arm_route_table.go index 7e6757545927..3e9571840038 100644 --- a/builtin/providers/azurerm/resource_arm_route_table.go +++ b/builtin/providers/azurerm/resource_arm_route_table.go @@ -1,258 +1,242 @@ package azurerm -//import ( -// "bytes" -// "fmt" -// "log" -// "net/http" -// "strings" -// "time" -// -// "github.com/Azure/azure-sdk-for-go/arm/network" -// "github.com/hashicorp/terraform/helper/hashcode" -// "github.com/hashicorp/terraform/helper/resource" -// "github.com/hashicorp/terraform/helper/schema" -//) -// -//func resourceArmRouteTable() *schema.Resource { -// return &schema.Resource{ -// Create: resourceArmRouteTableCreate, -// Read: resourceArmRouteTableRead, -// Update: resourceArmRouteTableCreate, -// Delete: resourceArmRouteTableDelete, -// -// Schema: map[string]*schema.Schema{ -// "name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// }, -// -// "location": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// StateFunc: azureRMNormalizeLocation, -// }, -// -// "resource_group_name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// }, -// -// "route": &schema.Schema{ -// Type: schema.TypeSet, -// Optional: true, -// Computed: true, -// Elem: &schema.Resource{ -// Schema: map[string]*schema.Schema{ -// "name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "address_prefix": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "next_hop_type": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ValidateFunc: validateRouteTableNextHopType, -// }, -// -// "next_hop_in_ip_address": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// Computed: true, -// }, -// }, -// }, -// Set: resourceArmRouteTableRouteHash, -// }, -// -// "subnets": &schema.Schema{ -// Type: schema.TypeSet, -// Optional: true, -// Computed: true, -// Elem: &schema.Schema{Type: schema.TypeString}, -// Set: schema.HashString, -// }, -// -// "tags": tagsSchema(), -// }, -// } -//} -// -//func resourceArmRouteTableCreate(d *schema.ResourceData, meta interface{}) error { -// client := meta.(*ArmClient) -// routeTablesClient := client.routeTablesClient -// -// log.Printf("[INFO] preparing arguments for Azure ARM Route Table creation.") -// -// name := d.Get("name").(string) -// location := d.Get("location").(string) -// resGroup := d.Get("resource_group_name").(string) -// tags := d.Get("tags").(map[string]interface{}) -// -// routeSet := network.RouteTable{ -// Name: &name, -// Location: &location, -// Tags: expandTags(tags), -// } -// -// if _, ok := d.GetOk("route"); ok { -// properties := network.RouteTablePropertiesFormat{} -// routes, routeErr := expandAzureRmRouteTableRoutes(d) -// if routeErr != nil { -// return fmt.Errorf("Error Building list of Route Table Routes: %s", routeErr) -// } -// if len(routes) > 0 { -// routeSet.Properties = &properties -// } -// -// } -// -// resp, err := routeTablesClient.CreateOrUpdate(resGroup, name, routeSet) -// if err != nil { -// return err -// } -// -// d.SetId(*resp.ID) -// -// log.Printf("[DEBUG] Waiting for Route Table (%s) to become available", name) -// stateConf := &resource.StateChangeConf{ -// Pending: []string{"Accepted", "Updating"}, -// Target: []string{"Succeeded"}, -// Refresh: routeTableStateRefreshFunc(client, resGroup, name), -// Timeout: 10 * time.Minute, -// } -// if _, err := stateConf.WaitForState(); err != nil { -// return fmt.Errorf("Error waiting forRoute Table (%s) to become available: %s", name, err) -// } -// -// return resourceArmRouteTableRead(d, meta) -//} -// -//func resourceArmRouteTableRead(d *schema.ResourceData, meta interface{}) error { -// routeTablesClient := meta.(*ArmClient).routeTablesClient -// -// id, err := parseAzureResourceID(d.Id()) -// if err != nil { -// return err -// } -// resGroup := id.ResourceGroup -// name := id.Path["routeTables"] -// -// resp, err := routeTablesClient.Get(resGroup, name, "") -// if resp.StatusCode == http.StatusNotFound { -// d.SetId("") -// return nil -// } -// if err != nil { -// return fmt.Errorf("Error making Read request on Azure Route Table %s: %s", name, err) -// } -// -// if resp.Properties.Subnets != nil { -// if len(*resp.Properties.Subnets) > 0 { -// subnets := make([]string, 0, len(*resp.Properties.Subnets)) -// for _, subnet := range *resp.Properties.Subnets { -// id := subnet.ID -// subnets = append(subnets, *id) -// } -// -// if err := d.Set("subnets", subnets); err != nil { -// return err -// } -// } -// } -// -// flattenAndSetTags(d, resp.Tags) -// -// return nil -//} -// -//func resourceArmRouteTableDelete(d *schema.ResourceData, meta interface{}) error { -// routeTablesClient := meta.(*ArmClient).routeTablesClient -// -// id, err := parseAzureResourceID(d.Id()) -// if err != nil { -// return err -// } -// resGroup := id.ResourceGroup -// name := id.Path["routeTables"] -// -// _, err = routeTablesClient.Delete(resGroup, name) -// -// return err -//} -// -//func expandAzureRmRouteTableRoutes(d *schema.ResourceData) ([]network.Route, error) { -// configs := d.Get("route").(*schema.Set).List() -// routes := make([]network.Route, 0, len(configs)) -// -// for _, configRaw := range configs { -// data := configRaw.(map[string]interface{}) -// -// address_prefix := data["address_prefix"].(string) -// next_hop_type := data["next_hop_type"].(string) -// -// properties := network.RoutePropertiesFormat{ -// AddressPrefix: &address_prefix, -// NextHopType: network.RouteNextHopType(next_hop_type), -// } -// -// if v := data["next_hop_in_ip_address"].(string); v != "" { -// properties.NextHopIPAddress = &v -// } -// -// name := data["name"].(string) -// route := network.Route{ -// Name: &name, -// Properties: &properties, -// } -// -// routes = append(routes, route) -// } -// -// return routes, nil -//} -// -//func routeTableStateRefreshFunc(client *ArmClient, resourceGroupName string, routeTableName string) resource.StateRefreshFunc { -// return func() (interface{}, string, error) { -// res, err := client.routeTablesClient.Get(resourceGroupName, routeTableName, "") -// if err != nil { -// return nil, "", fmt.Errorf("Error issuing read request in routeTableStateRefreshFunc to Azure ARM for route table '%s' (RG: '%s'): %s", routeTableName, resourceGroupName, err) -// } -// -// return res, *res.Properties.ProvisioningState, nil -// } -//} -// -//func resourceArmRouteTableRouteHash(v interface{}) int { -// var buf bytes.Buffer -// m := v.(map[string]interface{}) -// buf.WriteString(fmt.Sprintf("%s-", m["name"].(string))) -// buf.WriteString(fmt.Sprintf("%s-", m["address_prefix"].(string))) -// buf.WriteString(fmt.Sprintf("%s-", m["next_hop_type"].(string))) -// -// return hashcode.String(buf.String()) -//} -// -//func validateRouteTableNextHopType(v interface{}, k string) (ws []string, errors []error) { -// value := strings.ToLower(v.(string)) -// hopTypes := map[string]bool{ -// "virtualnetworkgateway": true, -// "vnetlocal": true, -// "internet": true, -// "virtualappliance": true, -// "none": true, -// } -// -// if !hopTypes[value] { -// errors = append(errors, fmt.Errorf("Route Table NextHopType Protocol can only be VirtualNetworkGateway, VnetLocal, Internet or VirtualAppliance")) -// } -// return -//} +import ( + "bytes" + "fmt" + "log" + "net/http" + "strings" + + "github.com/Azure/azure-sdk-for-go/arm/network" + "github.com/hashicorp/terraform/helper/hashcode" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceArmRouteTable() *schema.Resource { + return &schema.Resource{ + Create: resourceArmRouteTableCreate, + Read: resourceArmRouteTableRead, + Update: resourceArmRouteTableCreate, + Delete: resourceArmRouteTableDelete, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "location": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + StateFunc: azureRMNormalizeLocation, + }, + + "resource_group_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "route": { + Type: schema.TypeSet, + Optional: true, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + }, + + "address_prefix": { + Type: schema.TypeString, + Required: true, + }, + + "next_hop_type": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validateRouteTableNextHopType, + }, + + "next_hop_in_ip_address": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + }, + }, + Set: resourceArmRouteTableRouteHash, + }, + + "subnets": { + Type: schema.TypeSet, + Optional: true, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + Set: schema.HashString, + }, + + "tags": tagsSchema(), + }, + } +} + +func resourceArmRouteTableCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient) + routeTablesClient := client.routeTablesClient + + log.Printf("[INFO] preparing arguments for Azure ARM Route Table creation.") + + name := d.Get("name").(string) + location := d.Get("location").(string) + resGroup := d.Get("resource_group_name").(string) + tags := d.Get("tags").(map[string]interface{}) + + routeSet := network.RouteTable{ + Name: &name, + Location: &location, + Tags: expandTags(tags), + } + + if _, ok := d.GetOk("route"); ok { + properties := network.RouteTablePropertiesFormat{} + routes, routeErr := expandAzureRmRouteTableRoutes(d) + if routeErr != nil { + return fmt.Errorf("Error Building list of Route Table Routes: %s", routeErr) + } + if len(routes) > 0 { + routeSet.Properties = &properties + } + + } + + _, err := routeTablesClient.CreateOrUpdate(resGroup, name, routeSet, make(chan struct{})) + if err != nil { + return err + } + + read, err := routeTablesClient.Get(resGroup, name, "") + if err != nil { + return err + } + if read.ID == nil { + return fmt.Errorf("Cannot read Route Table %s (resource group %s) ID", name, resGroup) + } + + d.SetId(*read.ID) + + return resourceArmRouteTableRead(d, meta) +} + +func resourceArmRouteTableRead(d *schema.ResourceData, meta interface{}) error { + routeTablesClient := meta.(*ArmClient).routeTablesClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + name := id.Path["routeTables"] + + resp, err := routeTablesClient.Get(resGroup, name, "") + if resp.StatusCode == http.StatusNotFound { + d.SetId("") + return nil + } + if err != nil { + return fmt.Errorf("Error making Read request on Azure Route Table %s: %s", name, err) + } + + if resp.Properties.Subnets != nil { + if len(*resp.Properties.Subnets) > 0 { + subnets := make([]string, 0, len(*resp.Properties.Subnets)) + for _, subnet := range *resp.Properties.Subnets { + id := subnet.ID + subnets = append(subnets, *id) + } + + if err := d.Set("subnets", subnets); err != nil { + return err + } + } + } + + flattenAndSetTags(d, resp.Tags) + + return nil +} + +func resourceArmRouteTableDelete(d *schema.ResourceData, meta interface{}) error { + routeTablesClient := meta.(*ArmClient).routeTablesClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + name := id.Path["routeTables"] + + _, err = routeTablesClient.Delete(resGroup, name, make(chan struct{})) + + return err +} + +func expandAzureRmRouteTableRoutes(d *schema.ResourceData) ([]network.Route, error) { + configs := d.Get("route").(*schema.Set).List() + routes := make([]network.Route, 0, len(configs)) + + for _, configRaw := range configs { + data := configRaw.(map[string]interface{}) + + address_prefix := data["address_prefix"].(string) + next_hop_type := data["next_hop_type"].(string) + + properties := network.RoutePropertiesFormat{ + AddressPrefix: &address_prefix, + NextHopType: network.RouteNextHopType(next_hop_type), + } + + if v := data["next_hop_in_ip_address"].(string); v != "" { + properties.NextHopIPAddress = &v + } + + name := data["name"].(string) + route := network.Route{ + Name: &name, + Properties: &properties, + } + + routes = append(routes, route) + } + + return routes, nil +} + +func resourceArmRouteTableRouteHash(v interface{}) int { + var buf bytes.Buffer + m := v.(map[string]interface{}) + buf.WriteString(fmt.Sprintf("%s-", m["name"].(string))) + buf.WriteString(fmt.Sprintf("%s-", m["address_prefix"].(string))) + buf.WriteString(fmt.Sprintf("%s-", m["next_hop_type"].(string))) + + return hashcode.String(buf.String()) +} + +func validateRouteTableNextHopType(v interface{}, k string) (ws []string, errors []error) { + value := strings.ToLower(v.(string)) + hopTypes := map[string]bool{ + "virtualnetworkgateway": true, + "vnetlocal": true, + "internet": true, + "virtualappliance": true, + "none": true, + } + + if !hopTypes[value] { + errors = append(errors, fmt.Errorf("Route Table NextHopType Protocol can only be VirtualNetworkGateway, VnetLocal, Internet or VirtualAppliance")) + } + return +} diff --git a/builtin/providers/azurerm/resource_arm_route_table_test.go b/builtin/providers/azurerm/resource_arm_route_table_test.go index 92b9d01044d4..e6d978246386 100644 --- a/builtin/providers/azurerm/resource_arm_route_table_test.go +++ b/builtin/providers/azurerm/resource_arm_route_table_test.go @@ -1,294 +1,294 @@ 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 TestResourceAzureRMRouteTableNextHopType_validation(t *testing.T) { -// cases := []struct { -// Value string -// ErrCount int -// }{ -// { -// Value: "Random", -// ErrCount: 1, -// }, -// { -// Value: "VirtualNetworkGateway", -// ErrCount: 0, -// }, -// { -// Value: "VNETLocal", -// ErrCount: 0, -// }, -// { -// Value: "Internet", -// ErrCount: 0, -// }, -// { -// Value: "VirtualAppliance", -// ErrCount: 0, -// }, -// { -// Value: "None", -// ErrCount: 0, -// }, -// { -// Value: "VIRTUALNETWORKGATEWAY", -// ErrCount: 0, -// }, -// { -// Value: "virtualnetworkgateway", -// ErrCount: 0, -// }, -// } -// -// for _, tc := range cases { -// _, errors := validateRouteTableNextHopType(tc.Value, "azurerm_route_table") -// -// if len(errors) != tc.ErrCount { -// t.Fatalf("Expected the Azure RM Route Table nextHopType to trigger a validation error") -// } -// } -//} -// -//func TestAccAzureRMRouteTable_basic(t *testing.T) { -// -// ri := acctest.RandInt() -// config := fmt.Sprintf(testAccAzureRMRouteTable_basic, ri, ri) -// -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// Providers: testAccProviders, -// CheckDestroy: testCheckAzureRMRouteTableDestroy, -// Steps: []resource.TestStep{ -// resource.TestStep{ -// Config: config, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMRouteTableExists("azurerm_route_table.test"), -// ), -// }, -// }, -// }) -//} -// -//func TestAccAzureRMRouteTable_withTags(t *testing.T) { -// -// ri := acctest.RandInt() -// preConfig := fmt.Sprintf(testAccAzureRMRouteTable_withTags, ri, ri) -// postConfig := fmt.Sprintf(testAccAzureRMRouteTable_withTagsUpdate, ri, ri) -// -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// Providers: testAccProviders, -// CheckDestroy: testCheckAzureRMRouteTableDestroy, -// Steps: []resource.TestStep{ -// resource.TestStep{ -// Config: preConfig, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMRouteTableExists("azurerm_route_table.test"), -// resource.TestCheckResourceAttr( -// "azurerm_route_table.test", "tags.#", "2"), -// resource.TestCheckResourceAttr( -// "azurerm_route_table.test", "tags.environment", "Production"), -// resource.TestCheckResourceAttr( -// "azurerm_route_table.test", "tags.cost_center", "MSFT"), -// ), -// }, -// -// resource.TestStep{ -// Config: postConfig, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMRouteTableExists("azurerm_route_table.test"), -// resource.TestCheckResourceAttr( -// "azurerm_route_table.test", "tags.#", "1"), -// resource.TestCheckResourceAttr( -// "azurerm_route_table.test", "tags.environment", "staging"), -// ), -// }, -// }, -// }) -//} -// -//func TestAccAzureRMRouteTable_multipleRoutes(t *testing.T) { -// -// ri := acctest.RandInt() -// preConfig := fmt.Sprintf(testAccAzureRMRouteTable_basic, ri, ri) -// postConfig := fmt.Sprintf(testAccAzureRMRouteTable_multipleRoutes, ri, ri) -// -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// Providers: testAccProviders, -// CheckDestroy: testCheckAzureRMRouteTableDestroy, -// Steps: []resource.TestStep{ -// resource.TestStep{ -// Config: preConfig, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMRouteTableExists("azurerm_route_table.test"), -// resource.TestCheckResourceAttr( -// "azurerm_route_table.test", "route.#", "1"), -// ), -// }, -// -// resource.TestStep{ -// Config: postConfig, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMRouteTableExists("azurerm_route_table.test"), -// resource.TestCheckResourceAttr( -// "azurerm_route_table.test", "route.#", "2"), -// ), -// }, -// }, -// }) -//} -// -//func testCheckAzureRMRouteTableExists(name string) resource.TestCheckFunc { -// return func(s *terraform.State) error { -// -// rs, ok := s.RootModule().Resources[name] -// if !ok { -// return fmt.Errorf("Not found: %s", name) -// } -// -// name := rs.Primary.Attributes["name"] -// resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] -// if !hasResourceGroup { -// return fmt.Errorf("Bad: no resource group found in state for route table: %s", name) -// } -// -// conn := testAccProvider.Meta().(*ArmClient).routeTablesClient -// -// resp, err := conn.Get(resourceGroup, name, "") -// if err != nil { -// return fmt.Errorf("Bad: Get on routeTablesClient: %s", err) -// } -// -// if resp.StatusCode == http.StatusNotFound { -// return fmt.Errorf("Bad: Route Table %q (resource group: %q) does not exist", name, resourceGroup) -// } -// -// return nil -// } -//} -// -//func testCheckAzureRMRouteTableDestroy(s *terraform.State) error { -// conn := testAccProvider.Meta().(*ArmClient).routeTablesClient -// -// for _, rs := range s.RootModule().Resources { -// if rs.Type != "azurerm_route_table" { -// continue -// } -// -// name := rs.Primary.Attributes["name"] -// resourceGroup := rs.Primary.Attributes["resource_group_name"] -// -// resp, err := conn.Get(resourceGroup, name, "") -// -// if err != nil { -// return nil -// } -// -// if resp.StatusCode != http.StatusNotFound { -// return fmt.Errorf("Route Table still exists:\n%#v", resp.Properties) -// } -// } -// -// return nil -//} -// -//var testAccAzureRMRouteTable_basic = ` -//resource "azurerm_resource_group" "test" { -// name = "acctestrg-%d" -// location = "West US" -//} -// -//resource "azurerm_route_table" "test" { -// name = "acctestrt%d" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// -// route { -// name = "route1" -// address_prefix = "*" -// next_hop_type = "internet" -// } -//} -//` -// -//var testAccAzureRMRouteTable_multipleRoutes = ` -//resource "azurerm_resource_group" "test" { -// name = "acctestrg-%d" -// location = "West US" -//} -// -//resource "azurerm_route_table" "test" { -// name = "acctestrt%d" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// -// route { -// name = "route1" -// address_prefix = "*" -// next_hop_type = "internet" -// } -// -// route { -// name = "route2" -// address_prefix = "*" -// next_hop_type = "virtualappliance" -// } -//} -//` -// -//var testAccAzureRMRouteTable_withTags = ` -//resource "azurerm_resource_group" "test" { -// name = "acctestrg-%d" -// location = "West US" -//} -// -//resource "azurerm_route_table" "test" { -// name = "acctestrt%d" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// -// route { -// name = "route1" -// address_prefix = "*" -// next_hop_type = "internet" -// } -// -// tags { -// environment = "Production" -// cost_center = "MSFT" -// } -//} -//` -// -//var testAccAzureRMRouteTable_withTagsUpdate = ` -//resource "azurerm_resource_group" "test" { -// name = "acctestrg-%d" -// location = "West US" -//} -// -//resource "azurerm_route_table" "test" { -// name = "acctestrt%d" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// -// route { -// name = "route1" -// address_prefix = "*" -// next_hop_type = "internet" -// } -// -// tags { -// environment = "staging" -// } -//} -//` +import ( + "fmt" + "net/http" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestResourceAzureRMRouteTableNextHopType_validation(t *testing.T) { + cases := []struct { + Value string + ErrCount int + }{ + { + Value: "Random", + ErrCount: 1, + }, + { + Value: "VirtualNetworkGateway", + ErrCount: 0, + }, + { + Value: "VNETLocal", + ErrCount: 0, + }, + { + Value: "Internet", + ErrCount: 0, + }, + { + Value: "VirtualAppliance", + ErrCount: 0, + }, + { + Value: "None", + ErrCount: 0, + }, + { + Value: "VIRTUALNETWORKGATEWAY", + ErrCount: 0, + }, + { + Value: "virtualnetworkgateway", + ErrCount: 0, + }, + } + + for _, tc := range cases { + _, errors := validateRouteTableNextHopType(tc.Value, "azurerm_route_table") + + if len(errors) != tc.ErrCount { + t.Fatalf("Expected the Azure RM Route Table nextHopType to trigger a validation error") + } + } +} + +func TestAccAzureRMRouteTable_basic(t *testing.T) { + + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMRouteTable_basic, ri, ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMRouteTableDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMRouteTableExists("azurerm_route_table.test"), + ), + }, + }, + }) +} + +func TestAccAzureRMRouteTable_withTags(t *testing.T) { + + ri := acctest.RandInt() + preConfig := fmt.Sprintf(testAccAzureRMRouteTable_withTags, ri, ri) + postConfig := fmt.Sprintf(testAccAzureRMRouteTable_withTagsUpdate, ri, ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMRouteTableDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: preConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMRouteTableExists("azurerm_route_table.test"), + resource.TestCheckResourceAttr( + "azurerm_route_table.test", "tags.#", "2"), + resource.TestCheckResourceAttr( + "azurerm_route_table.test", "tags.environment", "Production"), + resource.TestCheckResourceAttr( + "azurerm_route_table.test", "tags.cost_center", "MSFT"), + ), + }, + + resource.TestStep{ + Config: postConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMRouteTableExists("azurerm_route_table.test"), + resource.TestCheckResourceAttr( + "azurerm_route_table.test", "tags.#", "1"), + resource.TestCheckResourceAttr( + "azurerm_route_table.test", "tags.environment", "staging"), + ), + }, + }, + }) +} + +func TestAccAzureRMRouteTable_multipleRoutes(t *testing.T) { + + ri := acctest.RandInt() + preConfig := fmt.Sprintf(testAccAzureRMRouteTable_basic, ri, ri) + postConfig := fmt.Sprintf(testAccAzureRMRouteTable_multipleRoutes, ri, ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMRouteTableDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: preConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMRouteTableExists("azurerm_route_table.test"), + resource.TestCheckResourceAttr( + "azurerm_route_table.test", "route.#", "1"), + ), + }, + + resource.TestStep{ + Config: postConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMRouteTableExists("azurerm_route_table.test"), + resource.TestCheckResourceAttr( + "azurerm_route_table.test", "route.#", "2"), + ), + }, + }, + }) +} + +func testCheckAzureRMRouteTableExists(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + name := rs.Primary.Attributes["name"] + resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] + if !hasResourceGroup { + return fmt.Errorf("Bad: no resource group found in state for route table: %s", name) + } + + conn := testAccProvider.Meta().(*ArmClient).routeTablesClient + + resp, err := conn.Get(resourceGroup, name, "") + if err != nil { + return fmt.Errorf("Bad: Get on routeTablesClient: %s", err) + } + + if resp.StatusCode == http.StatusNotFound { + return fmt.Errorf("Bad: Route Table %q (resource group: %q) does not exist", name, resourceGroup) + } + + return nil + } +} + +func testCheckAzureRMRouteTableDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*ArmClient).routeTablesClient + + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_route_table" { + continue + } + + name := rs.Primary.Attributes["name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] + + resp, err := conn.Get(resourceGroup, name, "") + + if err != nil { + return nil + } + + if resp.StatusCode != http.StatusNotFound { + return fmt.Errorf("Route Table still exists:\n%#v", resp.Properties) + } + } + + return nil +} + +var testAccAzureRMRouteTable_basic = ` +resource "azurerm_resource_group" "test" { + name = "acctestrg-%d" + location = "West US" +} + +resource "azurerm_route_table" "test" { + name = "acctestrt%d" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + + route { + name = "route1" + address_prefix = "*" + next_hop_type = "internet" + } +} +` + +var testAccAzureRMRouteTable_multipleRoutes = ` +resource "azurerm_resource_group" "test" { + name = "acctestrg-%d" + location = "West US" +} + +resource "azurerm_route_table" "test" { + name = "acctestrt%d" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + + route { + name = "route1" + address_prefix = "*" + next_hop_type = "internet" + } + + route { + name = "route2" + address_prefix = "*" + next_hop_type = "virtualappliance" + } +} +` + +var testAccAzureRMRouteTable_withTags = ` +resource "azurerm_resource_group" "test" { + name = "acctestrg-%d" + location = "West US" +} + +resource "azurerm_route_table" "test" { + name = "acctestrt%d" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + + route { + name = "route1" + address_prefix = "*" + next_hop_type = "internet" + } + + tags { + environment = "Production" + cost_center = "MSFT" + } +} +` + +var testAccAzureRMRouteTable_withTagsUpdate = ` +resource "azurerm_resource_group" "test" { + name = "acctestrg-%d" + location = "West US" +} + +resource "azurerm_route_table" "test" { + name = "acctestrt%d" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + + route { + name = "route1" + address_prefix = "*" + next_hop_type = "internet" + } + + tags { + environment = "staging" + } +} +` From a9b9986e76895add1785c8f68b9af69d096aaa23 Mon Sep 17 00:00:00 2001 From: James Nugent Date: Wed, 1 Jun 2016 18:34:25 -0500 Subject: [PATCH 09/17] provider/azurerm: Fix azurerm_route ``` HTTP_PROXY=http://localhost:8888 make testacc TEST=./builtin/providers/azurerm TESTARGS="-run TestAccAzureRMRoute_" ==> Checking that code complies with gofmt requirements... /Users/James/Code/go/bin/stringer go generate $(go list ./... | grep -v /vendor/) 2016/06/01 18:28:38 Generated command/internal_plugin_list.go TF_ACC=1 go test ./builtin/providers/azurerm -v -run TestAccAzureRMRoute_ -timeout 120m === RUN TestAccAzureRMRoute_basic --- PASS: TestAccAzureRMRoute_basic (98.80s) === RUN TestAccAzureRMRoute_multipleRoutes --- PASS: TestAccAzureRMRoute_multipleRoutes (130.77s) PASS ok github.com/hashicorp/terraform/builtin/providers/azurerm 229.584s ``` --- builtin/providers/azurerm/provider.go | 4 +- .../providers/azurerm/resource_arm_route.go | 301 ++++++++--------- .../azurerm/resource_arm_route_test.go | 314 +++++++++--------- 3 files changed, 301 insertions(+), 318 deletions(-) diff --git a/builtin/providers/azurerm/provider.go b/builtin/providers/azurerm/provider.go index 08788eef5f79..9d2fd1754c26 100644 --- a/builtin/providers/azurerm/provider.go +++ b/builtin/providers/azurerm/provider.go @@ -52,8 +52,8 @@ func Provider() terraform.ResourceProvider { //"azurerm_network_interface": resourceArmNetworkInterface(), //"azurerm_network_security_group": resourceArmNetworkSecurityGroup(), //"azurerm_network_security_rule": resourceArmNetworkSecurityRule(), - "azurerm_public_ip": resourceArmPublicIp(), - //"azurerm_route": resourceArmRoute(), + "azurerm_public_ip": resourceArmPublicIp(), + "azurerm_route": resourceArmRoute(), "azurerm_route_table": resourceArmRouteTable(), "azurerm_storage_account": resourceArmStorageAccount(), "azurerm_storage_blob": resourceArmStorageBlob(), diff --git a/builtin/providers/azurerm/resource_arm_route.go b/builtin/providers/azurerm/resource_arm_route.go index 965d7e3a3551..ae7b38279548 100644 --- a/builtin/providers/azurerm/resource_arm_route.go +++ b/builtin/providers/azurerm/resource_arm_route.go @@ -1,161 +1,144 @@ package azurerm -//import ( -// "fmt" -// "log" -// "net/http" -// "time" -// -// "github.com/Azure/azure-sdk-for-go/arm/network" -// "github.com/hashicorp/terraform/helper/resource" -// "github.com/hashicorp/terraform/helper/schema" -//) -// -//func resourceArmRoute() *schema.Resource { -// return &schema.Resource{ -// Create: resourceArmRouteCreate, -// Read: resourceArmRouteRead, -// Update: resourceArmRouteCreate, -// Delete: resourceArmRouteDelete, -// -// Schema: map[string]*schema.Schema{ -// "name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// }, -// -// "resource_group_name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// }, -// -// "route_table_name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// }, -// -// "address_prefix": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "next_hop_type": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ValidateFunc: validateRouteTableNextHopType, -// }, -// -// "next_hop_in_ip_address": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// Computed: true, -// }, -// }, -// } -//} -// -//func resourceArmRouteCreate(d *schema.ResourceData, meta interface{}) error { -// client := meta.(*ArmClient) -// routesClient := client.routesClient -// -// name := d.Get("name").(string) -// rtName := d.Get("route_table_name").(string) -// resGroup := d.Get("resource_group_name").(string) -// -// addressPrefix := d.Get("address_prefix").(string) -// nextHopType := d.Get("next_hop_type").(string) -// -// armMutexKV.Lock(rtName) -// defer armMutexKV.Unlock(rtName) -// -// properties := network.RoutePropertiesFormat{ -// AddressPrefix: &addressPrefix, -// NextHopType: network.RouteNextHopType(nextHopType), -// } -// -// if v, ok := d.GetOk("next_hop_in_ip_address"); ok { -// nextHopInIpAddress := v.(string) -// properties.NextHopIPAddress = &nextHopInIpAddress -// } -// -// route := network.Route{ -// Name: &name, -// Properties: &properties, -// } -// -// resp, err := routesClient.CreateOrUpdate(resGroup, rtName, name, route) -// if err != nil { -// return err -// } -// d.SetId(*resp.ID) -// -// log.Printf("[DEBUG] Waiting for Route (%s) to become available", name) -// stateConf := &resource.StateChangeConf{ -// Pending: []string{"Accepted", "Updating"}, -// Target: []string{"Succeeded"}, -// Refresh: routeStateRefreshFunc(client, resGroup, rtName, name), -// Timeout: 10 * time.Minute, -// } -// if _, err := stateConf.WaitForState(); err != nil { -// return fmt.Errorf("Error waiting for Route (%s) to become available: %s", name, err) -// } -// -// return resourceArmRouteRead(d, meta) -//} -// -//func resourceArmRouteRead(d *schema.ResourceData, meta interface{}) error { -// routesClient := meta.(*ArmClient).routesClient -// -// id, err := parseAzureResourceID(d.Id()) -// if err != nil { -// return err -// } -// resGroup := id.ResourceGroup -// rtName := id.Path["routeTables"] -// routeName := id.Path["routes"] -// -// resp, err := routesClient.Get(resGroup, rtName, routeName) -// if resp.StatusCode == http.StatusNotFound { -// d.SetId("") -// return nil -// } -// if err != nil { -// return fmt.Errorf("Error making Read request on Azure Route %s: %s", routeName, err) -// } -// -// return nil -//} -// -//func resourceArmRouteDelete(d *schema.ResourceData, meta interface{}) error { -// client := meta.(*ArmClient) -// routesClient := client.routesClient -// -// id, err := parseAzureResourceID(d.Id()) -// if err != nil { -// return err -// } -// resGroup := id.ResourceGroup -// rtName := id.Path["routeTables"] -// routeName := id.Path["routes"] -// -// armMutexKV.Lock(rtName) -// defer armMutexKV.Unlock(rtName) -// -// _, err = routesClient.Delete(resGroup, rtName, routeName) -// -// return err -//} -// -//func routeStateRefreshFunc(client *ArmClient, resourceGroupName string, routeTableName string, routeName string) resource.StateRefreshFunc { -// return func() (interface{}, string, error) { -// res, err := client.routesClient.Get(resourceGroupName, routeTableName, routeName) -// if err != nil { -// return nil, "", fmt.Errorf("Error issuing read request in routeStateRefreshFunc to Azure ARM for route '%s' (RG: '%s') (NSG: '%s'): %s", routeName, resourceGroupName, routeTableName, err) -// } -// -// return res, *res.Properties.ProvisioningState, nil -// } -//} +import ( + "fmt" + "net/http" + + "github.com/Azure/azure-sdk-for-go/arm/network" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceArmRoute() *schema.Resource { + return &schema.Resource{ + Create: resourceArmRouteCreate, + Read: resourceArmRouteRead, + Update: resourceArmRouteCreate, + Delete: resourceArmRouteDelete, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "resource_group_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "route_table_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "address_prefix": { + Type: schema.TypeString, + Required: true, + }, + + "next_hop_type": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validateRouteTableNextHopType, + }, + + "next_hop_in_ip_address": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + }, + } +} + +func resourceArmRouteCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient) + routesClient := client.routesClient + + name := d.Get("name").(string) + rtName := d.Get("route_table_name").(string) + resGroup := d.Get("resource_group_name").(string) + + addressPrefix := d.Get("address_prefix").(string) + nextHopType := d.Get("next_hop_type").(string) + + armMutexKV.Lock(rtName) + defer armMutexKV.Unlock(rtName) + + properties := network.RoutePropertiesFormat{ + AddressPrefix: &addressPrefix, + NextHopType: network.RouteNextHopType(nextHopType), + } + + if v, ok := d.GetOk("next_hop_in_ip_address"); ok { + nextHopInIpAddress := v.(string) + properties.NextHopIPAddress = &nextHopInIpAddress + } + + route := network.Route{ + Name: &name, + Properties: &properties, + } + + _, err := routesClient.CreateOrUpdate(resGroup, rtName, name, route, make(chan struct{})) + if err != nil { + return err + } + + read, err := routesClient.Get(resGroup, rtName, name) + if err != nil { + return err + } + if read.ID == nil { + return fmt.Errorf("Cannot read Route %s/%s (resource group %s) ID", rtName, name, resGroup) + } + d.SetId(*read.ID) + + return resourceArmRouteRead(d, meta) +} + +func resourceArmRouteRead(d *schema.ResourceData, meta interface{}) error { + routesClient := meta.(*ArmClient).routesClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + rtName := id.Path["routeTables"] + routeName := id.Path["routes"] + + resp, err := routesClient.Get(resGroup, rtName, routeName) + if resp.StatusCode == http.StatusNotFound { + d.SetId("") + return nil + } + if err != nil { + return fmt.Errorf("Error making Read request on Azure Route %s: %s", routeName, err) + } + + return nil +} + +func resourceArmRouteDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient) + routesClient := client.routesClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + rtName := id.Path["routeTables"] + routeName := id.Path["routes"] + + armMutexKV.Lock(rtName) + defer armMutexKV.Unlock(rtName) + + _, err = routesClient.Delete(resGroup, rtName, routeName, make(chan struct{})) + + return err +} diff --git a/builtin/providers/azurerm/resource_arm_route_test.go b/builtin/providers/azurerm/resource_arm_route_test.go index b98a6302b74a..6a664e9bfb5a 100644 --- a/builtin/providers/azurerm/resource_arm_route_test.go +++ b/builtin/providers/azurerm/resource_arm_route_test.go @@ -1,159 +1,159 @@ 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 TestAccAzureRMRoute_basic(t *testing.T) { -// -// ri := acctest.RandInt() -// config := fmt.Sprintf(testAccAzureRMRoute_basic, ri, ri, ri) -// -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// Providers: testAccProviders, -// CheckDestroy: testCheckAzureRMRouteDestroy, -// Steps: []resource.TestStep{ -// resource.TestStep{ -// Config: config, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMRouteExists("azurerm_route.test"), -// ), -// }, -// }, -// }) -//} -// -//func TestAccAzureRMRoute_multipleRoutes(t *testing.T) { -// -// ri := acctest.RandInt() -// preConfig := fmt.Sprintf(testAccAzureRMRoute_basic, ri, ri, ri) -// postConfig := fmt.Sprintf(testAccAzureRMRoute_multipleRoutes, ri, ri, ri) -// -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// Providers: testAccProviders, -// CheckDestroy: testCheckAzureRMRouteDestroy, -// Steps: []resource.TestStep{ -// resource.TestStep{ -// Config: preConfig, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMRouteExists("azurerm_route.test"), -// ), -// }, -// -// resource.TestStep{ -// Config: postConfig, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMRouteExists("azurerm_route.test1"), -// ), -// }, -// }, -// }) -//} -// -//func testCheckAzureRMRouteExists(name string) resource.TestCheckFunc { -// return func(s *terraform.State) error { -// -// rs, ok := s.RootModule().Resources[name] -// if !ok { -// return fmt.Errorf("Not found: %s", name) -// } -// -// name := rs.Primary.Attributes["name"] -// rtName := rs.Primary.Attributes["route_table_name"] -// resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] -// if !hasResourceGroup { -// return fmt.Errorf("Bad: no resource group found in state for route: %s", name) -// } -// -// conn := testAccProvider.Meta().(*ArmClient).routesClient -// -// resp, err := conn.Get(resourceGroup, rtName, name) -// if err != nil { -// return fmt.Errorf("Bad: Get on routesClient: %s", err) -// } -// -// if resp.StatusCode == http.StatusNotFound { -// return fmt.Errorf("Bad: Route %q (resource group: %q) does not exist", name, resourceGroup) -// } -// -// return nil -// } -//} -// -//func testCheckAzureRMRouteDestroy(s *terraform.State) error { -// conn := testAccProvider.Meta().(*ArmClient).routesClient -// -// for _, rs := range s.RootModule().Resources { -// if rs.Type != "azurerm_route" { -// continue -// } -// -// name := rs.Primary.Attributes["name"] -// rtName := rs.Primary.Attributes["route_table_name"] -// resourceGroup := rs.Primary.Attributes["resource_group_name"] -// -// resp, err := conn.Get(resourceGroup, rtName, name) -// -// if err != nil { -// return nil -// } -// -// if resp.StatusCode != http.StatusNotFound { -// return fmt.Errorf("Route still exists:\n%#v", resp.Properties) -// } -// } -// -// return nil -//} -// -//var testAccAzureRMRoute_basic = ` -//resource "azurerm_resource_group" "test" { -// name = "acctestrg-%d" -// location = "West US" -//} -// -//resource "azurerm_route_table" "test" { -// name = "acctestrt%d" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -//} -// -//resource "azurerm_route" "test" { -// name = "acctestroute%d" -// resource_group_name = "${azurerm_resource_group.test.name}" -// route_table_name = "${azurerm_route_table.test.name}" -// -// address_prefix = "10.1.0.0/16" -// next_hop_type = "vnetlocal" -//} -//` -// -//var testAccAzureRMRoute_multipleRoutes = ` -//resource "azurerm_resource_group" "test" { -// name = "acctestrg-%d" -// location = "West US" -//} -// -//resource "azurerm_route_table" "test" { -// name = "acctestrt%d" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -//} -// -//resource "azurerm_route" "test1" { -// name = "acctestroute%d" -// resource_group_name = "${azurerm_resource_group.test.name}" -// route_table_name = "${azurerm_route_table.test.name}" -// -// address_prefix = "10.2.0.0/16" -// next_hop_type = "none" -//} -//` +import ( + "fmt" + "net/http" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAzureRMRoute_basic(t *testing.T) { + + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMRoute_basic, ri, ri, ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMRouteDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMRouteExists("azurerm_route.test"), + ), + }, + }, + }) +} + +func TestAccAzureRMRoute_multipleRoutes(t *testing.T) { + + ri := acctest.RandInt() + preConfig := fmt.Sprintf(testAccAzureRMRoute_basic, ri, ri, ri) + postConfig := fmt.Sprintf(testAccAzureRMRoute_multipleRoutes, ri, ri, ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMRouteDestroy, + Steps: []resource.TestStep{ + { + Config: preConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMRouteExists("azurerm_route.test"), + ), + }, + + { + Config: postConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMRouteExists("azurerm_route.test1"), + ), + }, + }, + }) +} + +func testCheckAzureRMRouteExists(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + name := rs.Primary.Attributes["name"] + rtName := rs.Primary.Attributes["route_table_name"] + resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] + if !hasResourceGroup { + return fmt.Errorf("Bad: no resource group found in state for route: %s", name) + } + + conn := testAccProvider.Meta().(*ArmClient).routesClient + + resp, err := conn.Get(resourceGroup, rtName, name) + if err != nil { + return fmt.Errorf("Bad: Get on routesClient: %s", err) + } + + if resp.StatusCode == http.StatusNotFound { + return fmt.Errorf("Bad: Route %q (resource group: %q) does not exist", name, resourceGroup) + } + + return nil + } +} + +func testCheckAzureRMRouteDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*ArmClient).routesClient + + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_route" { + continue + } + + name := rs.Primary.Attributes["name"] + rtName := rs.Primary.Attributes["route_table_name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] + + resp, err := conn.Get(resourceGroup, rtName, name) + + if err != nil { + return nil + } + + if resp.StatusCode != http.StatusNotFound { + return fmt.Errorf("Route still exists:\n%#v", resp.Properties) + } + } + + return nil +} + +var testAccAzureRMRoute_basic = ` +resource "azurerm_resource_group" "test" { + name = "acctestrg-%d" + location = "West US" +} + +resource "azurerm_route_table" "test" { + name = "acctestrt%d" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" +} + +resource "azurerm_route" "test" { + name = "acctestroute%d" + resource_group_name = "${azurerm_resource_group.test.name}" + route_table_name = "${azurerm_route_table.test.name}" + + address_prefix = "10.1.0.0/16" + next_hop_type = "vnetlocal" +} +` + +var testAccAzureRMRoute_multipleRoutes = ` +resource "azurerm_resource_group" "test" { + name = "acctestrg-%d" + location = "West US" +} + +resource "azurerm_route_table" "test" { + name = "acctestrt%d" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" +} + +resource "azurerm_route" "test1" { + name = "acctestroute%d" + resource_group_name = "${azurerm_resource_group.test.name}" + route_table_name = "${azurerm_route_table.test.name}" + + address_prefix = "10.2.0.0/16" + next_hop_type = "none" +} +` From bde2c502b61a39d382b4c5c500e360f92da8e05d Mon Sep 17 00:00:00 2001 From: James Nugent Date: Wed, 1 Jun 2016 18:54:20 -0500 Subject: [PATCH 10/17] provider/azurerm: Fix azurerm_network_interface_card ``` HTTP_PROXY=http://localhost:8888 make testacc TEST=./builtin/providers/azurerm TESTARGS="-run TestAccAzureRMNetworkInterface" ==> Checking that code complies with gofmt requirements... /Users/James/Code/go/bin/stringer go generate $(go list ./... | grep -v /vendor/) 2016/06/01 18:46:41 Generated command/internal_plugin_list.go TF_ACC=1 go test ./builtin/providers/azurerm -v -run TestAccAzureRMNetworkInterface -timeout 120m === RUN TestAccAzureRMNetworkInterface_basic --- PASS: TestAccAzureRMNetworkInterface_basic (118.72s) === RUN TestAccAzureRMNetworkInterface_enableIPForwarding --- PASS: TestAccAzureRMNetworkInterface_enableIPForwarding (123.44s) === RUN TestAccAzureRMNetworkInterface_withTags --- PASS: TestAccAzureRMNetworkInterface_withTags (139.62s) PASS ok github.com/hashicorp/terraform/builtin/providers/azurerm 381.802s ``` --- builtin/providers/azurerm/provider.go | 2 +- .../resource_arm_network_interface_card.go | 854 +++++++++--------- ...esource_arm_network_interface_card_test.go | 575 ++++++------ 3 files changed, 711 insertions(+), 720 deletions(-) diff --git a/builtin/providers/azurerm/provider.go b/builtin/providers/azurerm/provider.go index 9d2fd1754c26..324e5a0a5542 100644 --- a/builtin/providers/azurerm/provider.go +++ b/builtin/providers/azurerm/provider.go @@ -49,7 +49,7 @@ func Provider() terraform.ResourceProvider { //"azurerm_cdn_endpoint": resourceArmCdnEndpoint(), //"azurerm_cdn_profile": resourceArmCdnProfile(), //"azurerm_local_network_gateway": resourceArmLocalNetworkGateway(), - //"azurerm_network_interface": resourceArmNetworkInterface(), + "azurerm_network_interface": resourceArmNetworkInterface(), //"azurerm_network_security_group": resourceArmNetworkSecurityGroup(), //"azurerm_network_security_rule": resourceArmNetworkSecurityRule(), "azurerm_public_ip": resourceArmPublicIp(), diff --git a/builtin/providers/azurerm/resource_arm_network_interface_card.go b/builtin/providers/azurerm/resource_arm_network_interface_card.go index 3207d3e87674..8e6771541d01 100644 --- a/builtin/providers/azurerm/resource_arm_network_interface_card.go +++ b/builtin/providers/azurerm/resource_arm_network_interface_card.go @@ -1,431 +1,427 @@ package azurerm -//import ( -// "bytes" -// "fmt" -// "log" -// "net/http" -// "strings" -// "time" -// -// "github.com/Azure/azure-sdk-for-go/arm/network" -// "github.com/hashicorp/terraform/helper/hashcode" -// "github.com/hashicorp/terraform/helper/resource" -// "github.com/hashicorp/terraform/helper/schema" -//) -// -//func resourceArmNetworkInterface() *schema.Resource { -// return &schema.Resource{ -// Create: resourceArmNetworkInterfaceCreate, -// Read: resourceArmNetworkInterfaceRead, -// Update: resourceArmNetworkInterfaceCreate, -// Delete: resourceArmNetworkInterfaceDelete, -// -// Schema: map[string]*schema.Schema{ -// "name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// }, -// -// "location": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// StateFunc: azureRMNormalizeLocation, -// }, -// -// "resource_group_name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// }, -// -// "network_security_group_id": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// Computed: true, -// }, -// -// "mac_address": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// Computed: true, -// }, -// -// "private_ip_address": &schema.Schema{ -// Type: schema.TypeString, -// Computed: true, -// }, -// -// "virtual_machine_id": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// Computed: true, -// }, -// -// "ip_configuration": &schema.Schema{ -// Type: schema.TypeSet, -// Required: true, -// Elem: &schema.Resource{ -// Schema: map[string]*schema.Schema{ -// "name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "subnet_id": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "private_ip_address": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// Computed: true, -// }, -// -// "private_ip_address_allocation": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ValidateFunc: validateNetworkInterfacePrivateIpAddressAllocation, -// }, -// -// "public_ip_address_id": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// Computed: true, -// }, -// -// "load_balancer_backend_address_pools_ids": &schema.Schema{ -// Type: schema.TypeSet, -// Optional: true, -// Computed: true, -// Elem: &schema.Schema{Type: schema.TypeString}, -// Set: schema.HashString, -// }, -// -// "load_balancer_inbound_nat_rules_ids": &schema.Schema{ -// Type: schema.TypeSet, -// Optional: true, -// Computed: true, -// Elem: &schema.Schema{Type: schema.TypeString}, -// Set: schema.HashString, -// }, -// }, -// }, -// Set: resourceArmNetworkInterfaceIpConfigurationHash, -// }, -// -// "dns_servers": &schema.Schema{ -// Type: schema.TypeSet, -// Optional: true, -// Computed: true, -// Elem: &schema.Schema{Type: schema.TypeString}, -// Set: schema.HashString, -// }, -// -// "internal_dns_name_label": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// Computed: true, -// }, -// -// "applied_dns_servers": &schema.Schema{ -// Type: schema.TypeSet, -// Optional: true, -// Computed: true, -// Elem: &schema.Schema{Type: schema.TypeString}, -// Set: schema.HashString, -// }, -// -// "internal_fqdn": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// Computed: true, -// }, -// -// "enable_ip_forwarding": &schema.Schema{ -// Type: schema.TypeBool, -// Optional: true, -// Default: false, -// }, -// -// "tags": tagsSchema(), -// }, -// } -//} -// -//func resourceArmNetworkInterfaceCreate(d *schema.ResourceData, meta interface{}) error { -// client := meta.(*ArmClient) -// ifaceClient := client.ifaceClient -// -// log.Printf("[INFO] preparing arguments for Azure ARM Network Interface creation.") -// -// name := d.Get("name").(string) -// location := d.Get("location").(string) -// resGroup := d.Get("resource_group_name").(string) -// enableIpForwarding := d.Get("enable_ip_forwarding").(bool) -// tags := d.Get("tags").(map[string]interface{}) -// -// properties := network.InterfacePropertiesFormat{ -// EnableIPForwarding: &enableIpForwarding, -// } -// -// if v, ok := d.GetOk("network_security_group_id"); ok { -// nsgId := v.(string) -// properties.NetworkSecurityGroup = &network.SecurityGroup{ -// ID: &nsgId, -// } -// } -// -// dns, hasDns := d.GetOk("dns_servers") -// nameLabel, hasNameLabel := d.GetOk("internal_dns_name_label") -// if hasDns || hasNameLabel { -// ifaceDnsSettings := network.InterfaceDNSSettings{} -// -// if hasDns { -// var dnsServers []string -// dns := dns.(*schema.Set).List() -// for _, v := range dns { -// str := v.(string) -// dnsServers = append(dnsServers, str) -// } -// ifaceDnsSettings.DNSServers = &dnsServers -// } -// -// if hasNameLabel { -// name_label := nameLabel.(string) -// ifaceDnsSettings.InternalDNSNameLabel = &name_label -// -// } -// -// properties.DNSSettings = &ifaceDnsSettings -// } -// -// ipConfigs, sgErr := expandAzureRmNetworkInterfaceIpConfigurations(d) -// if sgErr != nil { -// return fmt.Errorf("Error Building list of Network Interface IP Configurations: %s", sgErr) -// } -// if len(ipConfigs) > 0 { -// properties.IPConfigurations = &ipConfigs -// } -// -// iface := network.Interface{ -// Name: &name, -// Location: &location, -// Properties: &properties, -// Tags: expandTags(tags), -// } -// -// resp, err := ifaceClient.CreateOrUpdate(resGroup, name, iface) -// if err != nil { -// return err -// } -// -// d.SetId(*resp.ID) -// -// log.Printf("[DEBUG] Waiting for Network Interface (%s) to become available", name) -// stateConf := &resource.StateChangeConf{ -// Pending: []string{"Accepted", "Updating"}, -// Target: []string{"Succeeded"}, -// Refresh: networkInterfaceStateRefreshFunc(client, resGroup, name), -// Timeout: 10 * time.Minute, -// } -// if _, err := stateConf.WaitForState(); err != nil { -// return fmt.Errorf("Error waiting for Network Interface (%s) to become available: %s", name, err) -// } -// -// return resourceArmNetworkInterfaceRead(d, meta) -//} -// -//func resourceArmNetworkInterfaceRead(d *schema.ResourceData, meta interface{}) error { -// ifaceClient := meta.(*ArmClient).ifaceClient -// -// id, err := parseAzureResourceID(d.Id()) -// if err != nil { -// return err -// } -// resGroup := id.ResourceGroup -// name := id.Path["networkInterfaces"] -// -// resp, err := ifaceClient.Get(resGroup, name, "") -// if resp.StatusCode == http.StatusNotFound { -// d.SetId("") -// return nil -// } -// if err != nil { -// return fmt.Errorf("Error making Read request on Azure Network Interface %s: %s", name, err) -// } -// -// iface := *resp.Properties -// -// if iface.MacAddress != nil { -// if *iface.MacAddress != "" { -// d.Set("mac_address", iface.MacAddress) -// } -// } -// -// if iface.IPConfigurations != nil && len(*iface.IPConfigurations) > 0 { -// var privateIPAddress *string -// ///TODO: Change this to a loop when https://github.com/Azure/azure-sdk-for-go/issues/259 is fixed -// if (*iface.IPConfigurations)[0].Properties != nil { -// privateIPAddress = (*iface.IPConfigurations)[0].Properties.PrivateIPAddress -// } -// -// if *privateIPAddress != "" { -// d.Set("private_ip_address", *privateIPAddress) -// } -// } -// -// if iface.VirtualMachine != nil { -// if *iface.VirtualMachine.ID != "" { -// d.Set("virtual_machine_id", *iface.VirtualMachine.ID) -// } -// } -// -// if iface.DNSSettings != nil { -// if iface.DNSSettings.AppliedDNSServers != nil && len(*iface.DNSSettings.AppliedDNSServers) > 0 { -// dnsServers := make([]string, 0, len(*iface.DNSSettings.AppliedDNSServers)) -// for _, dns := range *iface.DNSSettings.AppliedDNSServers { -// dnsServers = append(dnsServers, dns) -// } -// -// if err := d.Set("applied_dns_servers", dnsServers); err != nil { -// return err -// } -// } -// -// if iface.DNSSettings.InternalFqdn != nil && *iface.DNSSettings.InternalFqdn != "" { -// d.Set("internal_fqdn", iface.DNSSettings.InternalFqdn) -// } -// } -// -// flattenAndSetTags(d, resp.Tags) -// -// return nil -//} -// -//func resourceArmNetworkInterfaceDelete(d *schema.ResourceData, meta interface{}) error { -// ifaceClient := meta.(*ArmClient).ifaceClient -// -// id, err := parseAzureResourceID(d.Id()) -// if err != nil { -// return err -// } -// resGroup := id.ResourceGroup -// name := id.Path["networkInterfaces"] -// -// _, err = ifaceClient.Delete(resGroup, name) -// -// return err -//} -// -//func networkInterfaceStateRefreshFunc(client *ArmClient, resourceGroupName string, ifaceName string) resource.StateRefreshFunc { -// return func() (interface{}, string, error) { -// res, err := client.ifaceClient.Get(resourceGroupName, ifaceName, "") -// if err != nil { -// return nil, "", fmt.Errorf("Error issuing read request in networkInterfaceStateRefreshFunc to Azure ARM for network interace '%s' (RG: '%s'): %s", ifaceName, resourceGroupName, err) -// } -// -// return res, *res.Properties.ProvisioningState, nil -// } -//} -// -//func resourceArmNetworkInterfaceIpConfigurationHash(v interface{}) int { -// var buf bytes.Buffer -// m := v.(map[string]interface{}) -// buf.WriteString(fmt.Sprintf("%s-", m["name"].(string))) -// buf.WriteString(fmt.Sprintf("%s-", m["subnet_id"].(string))) -// if m["private_ip_address"] != nil { -// buf.WriteString(fmt.Sprintf("%s-", m["private_ip_address"].(string))) -// } -// buf.WriteString(fmt.Sprintf("%s-", m["private_ip_address_allocation"].(string))) -// if m["public_ip_address_id"] != nil { -// buf.WriteString(fmt.Sprintf("%s-", m["public_ip_address_id"].(string))) -// } -// -// return hashcode.String(buf.String()) -//} -// -//func validateNetworkInterfacePrivateIpAddressAllocation(v interface{}, k string) (ws []string, errors []error) { -// value := strings.ToLower(v.(string)) -// allocations := map[string]bool{ -// "static": true, -// "dynamic": true, -// } -// -// if !allocations[value] { -// errors = append(errors, fmt.Errorf("Network Interface Allocations can only be Static or Dynamic")) -// } -// return -//} -// -//func expandAzureRmNetworkInterfaceIpConfigurations(d *schema.ResourceData) ([]network.InterfaceIPConfiguration, error) { -// configs := d.Get("ip_configuration").(*schema.Set).List() -// ipConfigs := make([]network.InterfaceIPConfiguration, 0, len(configs)) -// -// for _, configRaw := range configs { -// data := configRaw.(map[string]interface{}) -// -// subnet_id := data["subnet_id"].(string) -// private_ip_allocation_method := data["private_ip_address_allocation"].(string) -// -// properties := network.InterfaceIPConfigurationPropertiesFormat{ -// Subnet: &network.Subnet{ -// ID: &subnet_id, -// }, -// PrivateIPAllocationMethod: &private_ip_allocation_method, -// } -// -// if v := data["private_ip_address"].(string); v != "" { -// properties.PrivateIPAddress = &v -// } -// -// if v := data["public_ip_address_id"].(string); v != "" { -// properties.PublicIPAddress = &network.PublicIPAddress{ -// ID: &v, -// } -// } -// -// if v, ok := data["load_balancer_backend_address_pools_ids"]; ok { -// var ids []network.BackendAddressPool -// pools := v.(*schema.Set).List() -// for _, p := range pools { -// pool_id := p.(string) -// id := network.BackendAddressPool{ -// ID: &pool_id, -// } -// -// ids = append(ids, id) -// } -// -// properties.LoadBalancerBackendAddressPools = &ids -// } -// -// if v, ok := data["load_balancer_inbound_nat_rules_ids"]; ok { -// var natRules []network.InboundNatRule -// rules := v.(*schema.Set).List() -// for _, r := range rules { -// rule_id := r.(string) -// rule := network.InboundNatRule{ -// ID: &rule_id, -// } -// -// natRules = append(natRules, rule) -// } -// -// properties.LoadBalancerInboundNatRules = &natRules -// } -// -// name := data["name"].(string) -// ipConfig := network.InterfaceIPConfiguration{ -// Name: &name, -// Properties: &properties, -// } -// -// ipConfigs = append(ipConfigs, ipConfig) -// } -// -// return ipConfigs, nil -//} +import ( + "bytes" + "fmt" + "log" + "net/http" + "strings" + + "github.com/Azure/azure-sdk-for-go/arm/network" + "github.com/hashicorp/terraform/helper/hashcode" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceArmNetworkInterface() *schema.Resource { + return &schema.Resource{ + Create: resourceArmNetworkInterfaceCreate, + Read: resourceArmNetworkInterfaceRead, + Update: resourceArmNetworkInterfaceCreate, + Delete: resourceArmNetworkInterfaceDelete, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "location": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + StateFunc: azureRMNormalizeLocation, + }, + + "resource_group_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "network_security_group_id": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + + "mac_address": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + + "private_ip_address": { + Type: schema.TypeString, + Computed: true, + }, + + "virtual_machine_id": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + + "ip_configuration": { + Type: schema.TypeSet, + Required: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + }, + + "subnet_id": { + Type: schema.TypeString, + Required: true, + }, + + "private_ip_address": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + + "private_ip_address_allocation": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validateNetworkInterfacePrivateIpAddressAllocation, + }, + + "public_ip_address_id": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + + "load_balancer_backend_address_pools_ids": { + Type: schema.TypeSet, + Optional: true, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + Set: schema.HashString, + }, + + "load_balancer_inbound_nat_rules_ids": { + Type: schema.TypeSet, + Optional: true, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + Set: schema.HashString, + }, + }, + }, + Set: resourceArmNetworkInterfaceIpConfigurationHash, + }, + + "dns_servers": { + Type: schema.TypeSet, + Optional: true, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + Set: schema.HashString, + }, + + "internal_dns_name_label": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + + "applied_dns_servers": { + Type: schema.TypeSet, + Optional: true, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + Set: schema.HashString, + }, + + "internal_fqdn": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + + "enable_ip_forwarding": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + + "tags": tagsSchema(), + }, + } +} + +func resourceArmNetworkInterfaceCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient) + ifaceClient := client.ifaceClient + + log.Printf("[INFO] preparing arguments for Azure ARM Network Interface creation.") + + name := d.Get("name").(string) + location := d.Get("location").(string) + resGroup := d.Get("resource_group_name").(string) + enableIpForwarding := d.Get("enable_ip_forwarding").(bool) + tags := d.Get("tags").(map[string]interface{}) + + properties := network.InterfacePropertiesFormat{ + EnableIPForwarding: &enableIpForwarding, + } + + if v, ok := d.GetOk("network_security_group_id"); ok { + nsgId := v.(string) + properties.NetworkSecurityGroup = &network.SecurityGroup{ + ID: &nsgId, + } + } + + dns, hasDns := d.GetOk("dns_servers") + nameLabel, hasNameLabel := d.GetOk("internal_dns_name_label") + if hasDns || hasNameLabel { + ifaceDnsSettings := network.InterfaceDNSSettings{} + + if hasDns { + var dnsServers []string + dns := dns.(*schema.Set).List() + for _, v := range dns { + str := v.(string) + dnsServers = append(dnsServers, str) + } + ifaceDnsSettings.DNSServers = &dnsServers + } + + if hasNameLabel { + name_label := nameLabel.(string) + ifaceDnsSettings.InternalDNSNameLabel = &name_label + + } + + properties.DNSSettings = &ifaceDnsSettings + } + + ipConfigs, sgErr := expandAzureRmNetworkInterfaceIpConfigurations(d) + if sgErr != nil { + return fmt.Errorf("Error Building list of Network Interface IP Configurations: %s", sgErr) + } + if len(ipConfigs) > 0 { + properties.IPConfigurations = &ipConfigs + } + + iface := network.Interface{ + Name: &name, + Location: &location, + Properties: &properties, + Tags: expandTags(tags), + } + + _, err := ifaceClient.CreateOrUpdate(resGroup, name, iface, make(chan struct{})) + if err != nil { + return err + } + + read, err := ifaceClient.Get(resGroup, name, "") + if err != nil { + return err + } + if read.ID == nil { + return fmt.Errorf("Cannot read NIC %s (resource group %s) ID", name, resGroup) + } + + d.SetId(*read.ID) + + return resourceArmNetworkInterfaceRead(d, meta) +} + +func resourceArmNetworkInterfaceRead(d *schema.ResourceData, meta interface{}) error { + ifaceClient := meta.(*ArmClient).ifaceClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + name := id.Path["networkInterfaces"] + + resp, err := ifaceClient.Get(resGroup, name, "") + if resp.StatusCode == http.StatusNotFound { + d.SetId("") + return nil + } + if err != nil { + return fmt.Errorf("Error making Read request on Azure Network Interface %s: %s", name, err) + } + + iface := *resp.Properties + + if iface.MacAddress != nil { + if *iface.MacAddress != "" { + d.Set("mac_address", iface.MacAddress) + } + } + + if iface.IPConfigurations != nil && len(*iface.IPConfigurations) > 0 { + var privateIPAddress *string + ///TODO: Change this to a loop when https://github.com/Azure/azure-sdk-for-go/issues/259 is fixed + if (*iface.IPConfigurations)[0].Properties != nil { + privateIPAddress = (*iface.IPConfigurations)[0].Properties.PrivateIPAddress + } + + if *privateIPAddress != "" { + d.Set("private_ip_address", *privateIPAddress) + } + } + + if iface.VirtualMachine != nil { + if *iface.VirtualMachine.ID != "" { + d.Set("virtual_machine_id", *iface.VirtualMachine.ID) + } + } + + if iface.DNSSettings != nil { + if iface.DNSSettings.AppliedDNSServers != nil && len(*iface.DNSSettings.AppliedDNSServers) > 0 { + dnsServers := make([]string, 0, len(*iface.DNSSettings.AppliedDNSServers)) + for _, dns := range *iface.DNSSettings.AppliedDNSServers { + dnsServers = append(dnsServers, dns) + } + + if err := d.Set("applied_dns_servers", dnsServers); err != nil { + return err + } + } + + if iface.DNSSettings.InternalFqdn != nil && *iface.DNSSettings.InternalFqdn != "" { + d.Set("internal_fqdn", iface.DNSSettings.InternalFqdn) + } + } + + flattenAndSetTags(d, resp.Tags) + + return nil +} + +func resourceArmNetworkInterfaceDelete(d *schema.ResourceData, meta interface{}) error { + ifaceClient := meta.(*ArmClient).ifaceClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + name := id.Path["networkInterfaces"] + + _, err = ifaceClient.Delete(resGroup, name, make(chan struct{})) + + return err +} + +func resourceArmNetworkInterfaceIpConfigurationHash(v interface{}) int { + var buf bytes.Buffer + m := v.(map[string]interface{}) + buf.WriteString(fmt.Sprintf("%s-", m["name"].(string))) + buf.WriteString(fmt.Sprintf("%s-", m["subnet_id"].(string))) + if m["private_ip_address"] != nil { + buf.WriteString(fmt.Sprintf("%s-", m["private_ip_address"].(string))) + } + buf.WriteString(fmt.Sprintf("%s-", m["private_ip_address_allocation"].(string))) + if m["public_ip_address_id"] != nil { + buf.WriteString(fmt.Sprintf("%s-", m["public_ip_address_id"].(string))) + } + + return hashcode.String(buf.String()) +} + +func validateNetworkInterfacePrivateIpAddressAllocation(v interface{}, k string) (ws []string, errors []error) { + value := strings.ToLower(v.(string)) + allocations := map[string]bool{ + "static": true, + "dynamic": true, + } + + if !allocations[value] { + errors = append(errors, fmt.Errorf("Network Interface Allocations can only be Static or Dynamic")) + } + return +} + +func expandAzureRmNetworkInterfaceIpConfigurations(d *schema.ResourceData) ([]network.InterfaceIPConfiguration, error) { + configs := d.Get("ip_configuration").(*schema.Set).List() + ipConfigs := make([]network.InterfaceIPConfiguration, 0, len(configs)) + + for _, configRaw := range configs { + data := configRaw.(map[string]interface{}) + + subnet_id := data["subnet_id"].(string) + private_ip_allocation_method := data["private_ip_address_allocation"].(string) + + var allocationMethod network.IPAllocationMethod + switch strings.ToLower(private_ip_allocation_method) { + case "dynamic": + allocationMethod = network.Dynamic + case "static": + allocationMethod = network.Static + default: + return []network.InterfaceIPConfiguration{}, fmt.Errorf( + "valid values for private_ip_allocation_method are 'dynamic' and 'static' - got '%s'", + private_ip_allocation_method) + } + + properties := network.InterfaceIPConfigurationPropertiesFormat{ + Subnet: &network.Subnet{ + ID: &subnet_id, + }, + PrivateIPAllocationMethod: allocationMethod, + } + + if v := data["private_ip_address"].(string); v != "" { + properties.PrivateIPAddress = &v + } + + if v := data["public_ip_address_id"].(string); v != "" { + properties.PublicIPAddress = &network.PublicIPAddress{ + ID: &v, + } + } + + if v, ok := data["load_balancer_backend_address_pools_ids"]; ok { + var ids []network.BackendAddressPool + pools := v.(*schema.Set).List() + for _, p := range pools { + pool_id := p.(string) + id := network.BackendAddressPool{ + ID: &pool_id, + } + + ids = append(ids, id) + } + + properties.LoadBalancerBackendAddressPools = &ids + } + + if v, ok := data["load_balancer_inbound_nat_rules_ids"]; ok { + var natRules []network.InboundNatRule + rules := v.(*schema.Set).List() + for _, r := range rules { + rule_id := r.(string) + rule := network.InboundNatRule{ + ID: &rule_id, + } + + natRules = append(natRules, rule) + } + + properties.LoadBalancerInboundNatRules = &natRules + } + + name := data["name"].(string) + ipConfig := network.InterfaceIPConfiguration{ + Name: &name, + Properties: &properties, + } + + ipConfigs = append(ipConfigs, ipConfig) + } + + return ipConfigs, nil +} diff --git a/builtin/providers/azurerm/resource_arm_network_interface_card_test.go b/builtin/providers/azurerm/resource_arm_network_interface_card_test.go index 83149871ecbb..43df3a73ebb8 100644 --- a/builtin/providers/azurerm/resource_arm_network_interface_card_test.go +++ b/builtin/providers/azurerm/resource_arm_network_interface_card_test.go @@ -1,16 +1,82 @@ package azurerm -// -//import ( -// "fmt" -// "net/http" -// "testing" -// -// "github.com/hashicorp/terraform/helper/resource" -// "github.com/hashicorp/terraform/terraform" -//) -// -//func TestAccAzureRMNetworkInterface_basic(t *testing.T) { +import ( + "fmt" + "net/http" + "testing" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAzureRMNetworkInterface_basic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMNetworkInterfaceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMNetworkInterface_basic, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"), + ), + }, + }, + }) +} + +func TestAccAzureRMNetworkInterface_enableIPForwarding(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMNetworkInterfaceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMNetworkInterface_ipForwarding, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"), + resource.TestCheckResourceAttr( + "azurerm_network_interface.test", "enable_ip_forwarding", "true"), + ), + }, + }, + }) +} + +func TestAccAzureRMNetworkInterface_withTags(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMNetworkInterfaceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMNetworkInterface_withTags, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"), + resource.TestCheckResourceAttr( + "azurerm_network_interface.test", "tags.#", "2"), + resource.TestCheckResourceAttr( + "azurerm_network_interface.test", "tags.environment", "Production"), + resource.TestCheckResourceAttr( + "azurerm_network_interface.test", "tags.cost_center", "MSFT"), + ), + }, + { + Config: testAccAzureRMNetworkInterface_withTagsUpdate, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"), + resource.TestCheckResourceAttr( + "azurerm_network_interface.test", "tags.#", "1"), + resource.TestCheckResourceAttr( + "azurerm_network_interface.test", "tags.environment", "staging"), + ), + }, + }, + }) +} + +///TODO: Re-enable this test when https://github.com/Azure/azure-sdk-for-go/issues/259 is fixed +//func TestAccAzureRMNetworkInterface_addingIpConfigurations(t *testing.T) { // // resource.Test(t, resource.TestCase{ // PreCheck: func() { testAccPreCheck(t) }, @@ -21,182 +87,221 @@ package azurerm // Config: testAccAzureRMNetworkInterface_basic, // Check: resource.ComposeTestCheckFunc( // testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"), -// ), -// }, -// }, -// }) -//} -// -//func TestAccAzureRMNetworkInterfaceenableIPForwarding(t *testing.T) { -// -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// Providers: testAccProviders, -// CheckDestroy: testCheckAzureRMNetworkInterfaceDestroy, -// Steps: []resource.TestStep{ -// resource.TestStep{ -// Config: testAccAzureRMNetworkInterface_ipForwarding, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"), // resource.TestCheckResourceAttr( -// "azurerm_network_interface.test", "enable_ip_forwarding", "true"), +// "azurerm_network_interface.test", "ip_configuration.#", "1"), // ), // }, -// }, -// }) -//} -// -//func TestAccAzureRMNetworkInterface_withTags(t *testing.T) { // -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// Providers: testAccProviders, -// CheckDestroy: testCheckAzureRMNetworkInterfaceDestroy, -// Steps: []resource.TestStep{ // resource.TestStep{ -// Config: testAccAzureRMNetworkInterface_withTags, +// Config: testAccAzureRMNetworkInterface_extraIpConfiguration, // Check: resource.ComposeTestCheckFunc( // testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"), // resource.TestCheckResourceAttr( -// "azurerm_network_interface.test", "tags.#", "2"), -// resource.TestCheckResourceAttr( -// "azurerm_network_interface.test", "tags.environment", "Production"), -// resource.TestCheckResourceAttr( -// "azurerm_network_interface.test", "tags.cost_center", "MSFT"), -// ), -// }, -// -// resource.TestStep{ -// Config: testAccAzureRMNetworkInterface_withTagsUpdate, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"), -// resource.TestCheckResourceAttr( -// "azurerm_network_interface.test", "tags.#", "1"), -// resource.TestCheckResourceAttr( -// "azurerm_network_interface.test", "tags.environment", "staging"), +// "azurerm_network_interface.test", "ip_configuration.#", "2"), // ), // }, // }, // }) //} -// -/////TODO: Re-enable this test when https://github.com/Azure/azure-sdk-for-go/issues/259 is fixed -////func TestAccAzureRMNetworkInterface_addingIpConfigurations(t *testing.T) { -//// -//// resource.Test(t, resource.TestCase{ -//// PreCheck: func() { testAccPreCheck(t) }, -//// Providers: testAccProviders, -//// CheckDestroy: testCheckAzureRMNetworkInterfaceDestroy, -//// Steps: []resource.TestStep{ -//// resource.TestStep{ -//// Config: testAccAzureRMNetworkInterface_basic, -//// Check: resource.ComposeTestCheckFunc( -//// testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"), -//// resource.TestCheckResourceAttr( -//// "azurerm_network_interface.test", "ip_configuration.#", "1"), -//// ), -//// }, -//// -//// resource.TestStep{ -//// Config: testAccAzureRMNetworkInterface_extraIpConfiguration, -//// Check: resource.ComposeTestCheckFunc( -//// testCheckAzureRMNetworkInterfaceExists("azurerm_network_interface.test"), -//// resource.TestCheckResourceAttr( -//// "azurerm_network_interface.test", "ip_configuration.#", "2"), -//// ), -//// }, -//// }, -//// }) -////} -// -//func testCheckAzureRMNetworkInterfaceExists(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) -// } -// -// name := rs.Primary.Attributes["name"] -// resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] -// if !hasResourceGroup { -// return fmt.Errorf("Bad: no resource group found in state for availability set: %s", name) -// } -// -// conn := testAccProvider.Meta().(*ArmClient).ifaceClient -// -// resp, err := conn.Get(resourceGroup, name, "") -// if err != nil { -// return fmt.Errorf("Bad: Get on ifaceClient: %s", err) -// } -// -// if resp.StatusCode == http.StatusNotFound { -// return fmt.Errorf("Bad: Network Interface %q (resource group: %q) does not exist", name, resourceGroup) -// } -// -// return nil -// } -//} -// -//func testCheckAzureRMNetworkInterfaceDestroy(s *terraform.State) error { -// conn := testAccProvider.Meta().(*ArmClient).ifaceClient -// -// for _, rs := range s.RootModule().Resources { -// if rs.Type != "azurerm_network_interface" { -// continue -// } -// -// name := rs.Primary.Attributes["name"] -// resourceGroup := rs.Primary.Attributes["resource_group_name"] -// -// resp, err := conn.Get(resourceGroup, name, "") -// -// if err != nil { -// return nil -// } -// -// if resp.StatusCode != http.StatusNotFound { -// return fmt.Errorf("Network Interface still exists:\n%#v", resp.Properties) -// } -// } -// -// return nil -//} -// -//var testAccAzureRMNetworkInterface_basic = ` -//resource "azurerm_resource_group" "test" { -// name = "acceptanceTestResourceGroup1" -// location = "West US" -//} -// -//resource "azurerm_virtual_network" "test" { -// name = "acceptanceTestVirtualNetwork1" -// address_space = ["10.0.0.0/16"] -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -//} -// -//resource "azurerm_subnet" "test" { -// name = "testsubnet" -// resource_group_name = "${azurerm_resource_group.test.name}" -// virtual_network_name = "${azurerm_virtual_network.test.name}" -// address_prefix = "10.0.2.0/24" -//} -// -//resource "azurerm_network_interface" "test" { -// name = "acceptanceTestNetworkInterface1" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// -// ip_configuration { -// name = "testconfiguration1" -// subnet_id = "${azurerm_subnet.test.id}" -// private_ip_address_allocation = "dynamic" -// } -//} -//` -// -//var testAccAzureRMNetworkInterface_ipForwarding = ` + +func testCheckAzureRMNetworkInterfaceExists(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) + } + + name := rs.Primary.Attributes["name"] + resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] + if !hasResourceGroup { + return fmt.Errorf("Bad: no resource group found in state for availability set: %s", name) + } + + conn := testAccProvider.Meta().(*ArmClient).ifaceClient + + resp, err := conn.Get(resourceGroup, name, "") + if err != nil { + return fmt.Errorf("Bad: Get on ifaceClient: %s", err) + } + + if resp.StatusCode == http.StatusNotFound { + return fmt.Errorf("Bad: Network Interface %q (resource group: %q) does not exist", name, resourceGroup) + } + + return nil + } +} + +func testCheckAzureRMNetworkInterfaceDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*ArmClient).ifaceClient + + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_network_interface" { + continue + } + + name := rs.Primary.Attributes["name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] + + resp, err := conn.Get(resourceGroup, name, "") + + if err != nil { + return nil + } + + if resp.StatusCode != http.StatusNotFound { + return fmt.Errorf("Network Interface still exists:\n%#v", resp.Properties) + } + } + + return nil +} + +var testAccAzureRMNetworkInterface_basic = ` +resource "azurerm_resource_group" "test" { + name = "acceptanceTestResourceGroup1" + location = "West US" +} + +resource "azurerm_virtual_network" "test" { + name = "acceptanceTestVirtualNetwork1" + address_space = ["10.0.0.0/16"] + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" +} + +resource "azurerm_subnet" "test" { + name = "testsubnet" + resource_group_name = "${azurerm_resource_group.test.name}" + virtual_network_name = "${azurerm_virtual_network.test.name}" + address_prefix = "10.0.2.0/24" +} + +resource "azurerm_network_interface" "test" { + name = "acceptanceTestNetworkInterface1" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + + ip_configuration { + name = "testconfiguration1" + subnet_id = "${azurerm_subnet.test.id}" + private_ip_address_allocation = "dynamic" + } +} +` + +var testAccAzureRMNetworkInterface_ipForwarding = ` +resource "azurerm_resource_group" "test" { + name = "acceptanceTestResourceGroup1" + location = "West US" +} + +resource "azurerm_virtual_network" "test" { + name = "acceptanceTestVirtualNetwork1" + address_space = ["10.0.0.0/16"] + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" +} + +resource "azurerm_subnet" "test" { + name = "testsubnet" + resource_group_name = "${azurerm_resource_group.test.name}" + virtual_network_name = "${azurerm_virtual_network.test.name}" + address_prefix = "10.0.2.0/24" +} + +resource "azurerm_network_interface" "test" { + name = "acceptanceTestNetworkInterface1" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + enable_ip_forwarding = true + + ip_configuration { + name = "testconfiguration1" + subnet_id = "${azurerm_subnet.test.id}" + private_ip_address_allocation = "dynamic" + } +} +` + +var testAccAzureRMNetworkInterface_withTags = ` +resource "azurerm_resource_group" "test" { + name = "acceptanceTestResourceGroup1" + location = "West US" +} + +resource "azurerm_virtual_network" "test" { + name = "acceptanceTestVirtualNetwork1" + address_space = ["10.0.0.0/16"] + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" +} + +resource "azurerm_subnet" "test" { + name = "testsubnet" + resource_group_name = "${azurerm_resource_group.test.name}" + virtual_network_name = "${azurerm_virtual_network.test.name}" + address_prefix = "10.0.2.0/24" +} + +resource "azurerm_network_interface" "test" { + name = "acceptanceTestNetworkInterface1" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + + ip_configuration { + name = "testconfiguration1" + subnet_id = "${azurerm_subnet.test.id}" + private_ip_address_allocation = "dynamic" + } + + tags { + environment = "Production" + cost_center = "MSFT" + } +} +` + +var testAccAzureRMNetworkInterface_withTagsUpdate = ` +resource "azurerm_resource_group" "test" { + name = "acceptanceTestResourceGroup1" + location = "West US" +} + +resource "azurerm_virtual_network" "test" { + name = "acceptanceTestVirtualNetwork1" + address_space = ["10.0.0.0/16"] + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" +} + +resource "azurerm_subnet" "test" { + name = "testsubnet" + resource_group_name = "${azurerm_resource_group.test.name}" + virtual_network_name = "${azurerm_virtual_network.test.name}" + address_prefix = "10.0.2.0/24" +} + +resource "azurerm_network_interface" "test" { + name = "acceptanceTestNetworkInterface1" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + + ip_configuration { + name = "testconfiguration1" + subnet_id = "${azurerm_subnet.test.id}" + private_ip_address_allocation = "dynamic" + } + + tags { + environment = "staging" + } +} +` + +//TODO: Re-enable this test when https://github.com/Azure/azure-sdk-for-go/issues/259 is fixed +//var testAccAzureRMNetworkInterface_extraIpConfiguration = ` //resource "azurerm_resource_group" "test" { // name = "acceptanceTestResourceGroup1" // location = "West US" @@ -216,38 +321,11 @@ package azurerm // address_prefix = "10.0.2.0/24" //} // -//resource "azurerm_network_interface" "test" { -// name = "acceptanceTestNetworkInterface1" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// enable_ip_forwarding = true -// -// ip_configuration { -// name = "testconfiguration1" -// subnet_id = "${azurerm_subnet.test.id}" -// private_ip_address_allocation = "dynamic" -// } -//} -//` -// -//var testAccAzureRMNetworkInterface_withTags = ` -//resource "azurerm_resource_group" "test" { -// name = "acceptanceTestResourceGroup1" -// location = "West US" -//} -// -//resource "azurerm_virtual_network" "test" { -// name = "acceptanceTestVirtualNetwork1" -// address_space = ["10.0.0.0/16"] -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -//} -// -//resource "azurerm_subnet" "test" { -// name = "testsubnet" +//resource "azurerm_subnet" "test1" { +// name = "testsubnet1" // resource_group_name = "${azurerm_resource_group.test.name}" // virtual_network_name = "${azurerm_virtual_network.test.name}" -// address_prefix = "10.0.2.0/24" +// address_prefix = "10.0.1.0/24" //} // //resource "azurerm_network_interface" "test" { @@ -261,94 +339,11 @@ package azurerm // private_ip_address_allocation = "dynamic" // } // -// tags { -// environment = "Production" -// cost_center = "MSFT" -// } -//} -//` -// -//var testAccAzureRMNetworkInterface_withTagsUpdate = ` -//resource "azurerm_resource_group" "test" { -// name = "acceptanceTestResourceGroup1" -// location = "West US" -//} -// -//resource "azurerm_virtual_network" "test" { -// name = "acceptanceTestVirtualNetwork1" -// address_space = ["10.0.0.0/16"] -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -//} -// -//resource "azurerm_subnet" "test" { -// name = "testsubnet" -// resource_group_name = "${azurerm_resource_group.test.name}" -// virtual_network_name = "${azurerm_virtual_network.test.name}" -// address_prefix = "10.0.2.0/24" -//} -// -//resource "azurerm_network_interface" "test" { -// name = "acceptanceTestNetworkInterface1" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// // ip_configuration { -// name = "testconfiguration1" -// subnet_id = "${azurerm_subnet.test.id}" +// name = "testconfiguration2" +// subnet_id = "${azurerm_subnet.test1.id}" // private_ip_address_allocation = "dynamic" -// } -// -// tags { -// environment = "staging" +// primary = true // } //} //` -// -////TODO: Re-enable this test when https://github.com/Azure/azure-sdk-for-go/issues/259 is fixed -////var testAccAzureRMNetworkInterface_extraIpConfiguration = ` -////resource "azurerm_resource_group" "test" { -//// name = "acceptanceTestResourceGroup1" -//// location = "West US" -////} -//// -////resource "azurerm_virtual_network" "test" { -//// name = "acceptanceTestVirtualNetwork1" -//// address_space = ["10.0.0.0/16"] -//// location = "West US" -//// resource_group_name = "${azurerm_resource_group.test.name}" -////} -//// -////resource "azurerm_subnet" "test" { -//// name = "testsubnet" -//// resource_group_name = "${azurerm_resource_group.test.name}" -//// virtual_network_name = "${azurerm_virtual_network.test.name}" -//// address_prefix = "10.0.2.0/24" -////} -//// -////resource "azurerm_subnet" "test1" { -//// name = "testsubnet1" -//// resource_group_name = "${azurerm_resource_group.test.name}" -//// virtual_network_name = "${azurerm_virtual_network.test.name}" -//// address_prefix = "10.0.1.0/24" -////} -//// -////resource "azurerm_network_interface" "test" { -//// name = "acceptanceTestNetworkInterface1" -//// location = "West US" -//// resource_group_name = "${azurerm_resource_group.test.name}" -//// -//// ip_configuration { -//// name = "testconfiguration1" -//// subnet_id = "${azurerm_subnet.test.id}" -//// private_ip_address_allocation = "dynamic" -//// } -//// -//// ip_configuration { -//// name = "testconfiguration2" -//// subnet_id = "${azurerm_subnet.test1.id}" -//// private_ip_address_allocation = "dynamic" -//// primary = true -//// } -////} -////` From 0e3da1f98cebafa67d4863d203be0026db90804d Mon Sep 17 00:00:00 2001 From: James Nugent Date: Wed, 1 Jun 2016 19:02:04 -0500 Subject: [PATCH 11/17] provider/azurerm: Fix azurerm_local_network_gateway ``` HTTP_PROXY=http://localhost:8888 make testacc TEST=./builtin/providers/azurerm TESTARGS="-run TestAccAzureRMLocalNetworkGateway_" ==> Checking that code complies with gofmt requirements... /Users/James/Code/go/bin/stringer go generate $(go list ./... | grep -v /vendor/) 2016/06/01 18:59:05 Generated command/internal_plugin_list.go TF_ACC=1 go test ./builtin/providers/azurerm -v -run TestAccAzureRMLocalNetworkGateway_ -timeout 120m === RUN TestAccAzureRMLocalNetworkGateway_basic --- PASS: TestAccAzureRMLocalNetworkGateway_basic (95.25s) PASS ok github.com/hashicorp/terraform/builtin/providers/azurerm 95.260s ``` --- builtin/providers/azurerm/provider.go | 4 +- .../resource_arm_local_network_gateway.go | 278 +++++++++--------- ...resource_arm_local_network_gateway_test.go | 212 ++++++------- 3 files changed, 252 insertions(+), 242 deletions(-) diff --git a/builtin/providers/azurerm/provider.go b/builtin/providers/azurerm/provider.go index 324e5a0a5542..f660155e9d01 100644 --- a/builtin/providers/azurerm/provider.go +++ b/builtin/providers/azurerm/provider.go @@ -48,8 +48,8 @@ func Provider() terraform.ResourceProvider { "azurerm_availability_set": resourceArmAvailabilitySet(), //"azurerm_cdn_endpoint": resourceArmCdnEndpoint(), //"azurerm_cdn_profile": resourceArmCdnProfile(), - //"azurerm_local_network_gateway": resourceArmLocalNetworkGateway(), - "azurerm_network_interface": resourceArmNetworkInterface(), + "azurerm_local_network_gateway": resourceArmLocalNetworkGateway(), + "azurerm_network_interface": resourceArmNetworkInterface(), //"azurerm_network_security_group": resourceArmNetworkSecurityGroup(), //"azurerm_network_security_rule": resourceArmNetworkSecurityRule(), "azurerm_public_ip": resourceArmPublicIp(), diff --git a/builtin/providers/azurerm/resource_arm_local_network_gateway.go b/builtin/providers/azurerm/resource_arm_local_network_gateway.go index 9eeda5070862..1a4c4dcae9e2 100644 --- a/builtin/providers/azurerm/resource_arm_local_network_gateway.go +++ b/builtin/providers/azurerm/resource_arm_local_network_gateway.go @@ -1,136 +1,146 @@ package azurerm -//import ( -// "fmt" -// -// "github.com/Azure/azure-sdk-for-go/arm/network" -// "github.com/Azure/azure-sdk-for-go/core/http" -// "github.com/hashicorp/terraform/helper/schema" -//) -// -//func resourceArmLocalNetworkGateway() *schema.Resource { -// return &schema.Resource{ -// Create: resourceArmLocalNetworkGatewayCreate, -// Read: resourceArmLocalNetworkGatewayRead, -// Update: resourceArmLocalNetworkGatewayCreate, -// Delete: resourceArmLocalNetworkGatewayDelete, -// -// Schema: map[string]*schema.Schema{ -// "name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// }, -// -// "location": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// ForceNew: true, -// StateFunc: azureRMNormalizeLocation, -// }, -// -// "resource_group_name": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// ForceNew: true, -// }, -// -// "gateway_address": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "address_space": &schema.Schema{ -// Type: schema.TypeList, -// Required: true, -// Elem: &schema.Schema{ -// Type: schema.TypeString, -// }, -// }, -// }, -// } -//} -// -//func resourceArmLocalNetworkGatewayCreate(d *schema.ResourceData, meta interface{}) error { -// lnetClient := meta.(*ArmClient).localNetConnClient -// -// name := d.Get("name").(string) -// location := d.Get("location").(string) -// resGroup := d.Get("resource_group_name").(string) -// ipAddress := d.Get("gateway_address").(string) -// -// // fetch the 'address_space_prefixes: -// prefixes := []string{} -// for _, pref := range d.Get("address_space").([]interface{}) { -// prefixes = append(prefixes, pref.(string)) -// } -// -// resp, err := lnetClient.CreateOrUpdate(resGroup, name, network.LocalNetworkGateway{ -// Name: &name, -// Location: &location, -// Properties: &network.LocalNetworkGatewayPropertiesFormat{ -// LocalNetworkAddressSpace: &network.AddressSpace{ -// AddressPrefixes: &prefixes, -// }, -// GatewayIPAddress: &ipAddress, -// }, -// }) -// if err != nil { -// return fmt.Errorf("Error creating Azure ARM Local Network Gateway '%s': %s", name, err) -// } -// -// d.SetId(*resp.ID) -// -// return resourceArmLocalNetworkGatewayRead(d, meta) -//} -// -//// resourceArmLocalNetworkGatewayRead goes ahead and reads the state of the corresponding ARM local network gateway. -//func resourceArmLocalNetworkGatewayRead(d *schema.ResourceData, meta interface{}) error { -// lnetClient := meta.(*ArmClient).localNetConnClient -// -// id, err := parseAzureResourceID(d.Id()) -// if err != nil { -// return err -// } -// name := id.Path["localNetworkGateways"] -// resGroup := id.ResourceGroup -// -// resp, err := lnetClient.Get(resGroup, name) -// if err != nil { -// if resp.StatusCode == http.StatusNotFound { -// d.SetId("") -// return nil -// } -// -// return fmt.Errorf("Error reading the state of Azure ARM local network gateway '%s': %s", name, err) -// } -// -// d.Set("gateway_address", resp.Properties.GatewayIPAddress) -// -// prefs := []string{} -// if ps := *resp.Properties.LocalNetworkAddressSpace.AddressPrefixes; ps != nil { -// prefs = ps -// } -// d.Set("address_space", prefs) -// -// return nil -//} -// -//// resourceArmLocalNetworkGatewayDelete deletes the specified ARM local network gateway. -//func resourceArmLocalNetworkGatewayDelete(d *schema.ResourceData, meta interface{}) error { -// lnetClient := meta.(*ArmClient).localNetConnClient -// -// id, err := parseAzureResourceID(d.Id()) -// if err != nil { -// return err -// } -// name := id.Path["localNetworkGateways"] -// resGroup := id.ResourceGroup -// -// _, err = lnetClient.Delete(resGroup, name) -// if err != nil { -// return fmt.Errorf("Error issuing Azure ARM delete request of local network gateway '%s': %s", name, err) -// } -// -// return nil -//} +import ( + "fmt" + + "github.com/Azure/azure-sdk-for-go/arm/network" + "github.com/Azure/azure-sdk-for-go/core/http" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceArmLocalNetworkGateway() *schema.Resource { + return &schema.Resource{ + Create: resourceArmLocalNetworkGatewayCreate, + Read: resourceArmLocalNetworkGatewayRead, + Update: resourceArmLocalNetworkGatewayCreate, + Delete: resourceArmLocalNetworkGatewayDelete, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "location": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + StateFunc: azureRMNormalizeLocation, + }, + + "resource_group_name": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + + "gateway_address": { + Type: schema.TypeString, + Required: true, + }, + + "address_space": { + Type: schema.TypeList, + Required: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + }, + } +} + +func resourceArmLocalNetworkGatewayCreate(d *schema.ResourceData, meta interface{}) error { + lnetClient := meta.(*ArmClient).localNetConnClient + + name := d.Get("name").(string) + location := d.Get("location").(string) + resGroup := d.Get("resource_group_name").(string) + ipAddress := d.Get("gateway_address").(string) + + // fetch the 'address_space_prefixes: + prefixes := []string{} + for _, pref := range d.Get("address_space").([]interface{}) { + prefixes = append(prefixes, pref.(string)) + } + + gateway := network.LocalNetworkGateway{ + Name: &name, + Location: &location, + Properties: &network.LocalNetworkGatewayPropertiesFormat{ + LocalNetworkAddressSpace: &network.AddressSpace{ + AddressPrefixes: &prefixes, + }, + GatewayIPAddress: &ipAddress, + }, + } + + _, err := lnetClient.CreateOrUpdate(resGroup, name, gateway, make(chan struct{})) + if err != nil { + return fmt.Errorf("Error creating Azure ARM Local Network Gateway '%s': %s", name, err) + } + + read, err := lnetClient.Get(resGroup, name) + if err != nil { + return err + } + if read.ID == nil { + return fmt.Errorf("Cannot read Virtual Network %s (resource group %s) ID", name, resGroup) + } + + d.SetId(*read.ID) + + return resourceArmLocalNetworkGatewayRead(d, meta) +} + +// resourceArmLocalNetworkGatewayRead goes ahead and reads the state of the corresponding ARM local network gateway. +func resourceArmLocalNetworkGatewayRead(d *schema.ResourceData, meta interface{}) error { + lnetClient := meta.(*ArmClient).localNetConnClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + name := id.Path["localNetworkGateways"] + resGroup := id.ResourceGroup + + resp, err := lnetClient.Get(resGroup, name) + if err != nil { + if resp.StatusCode == http.StatusNotFound { + d.SetId("") + return nil + } + + return fmt.Errorf("Error reading the state of Azure ARM local network gateway '%s': %s", name, err) + } + + d.Set("gateway_address", resp.Properties.GatewayIPAddress) + + prefs := []string{} + if ps := *resp.Properties.LocalNetworkAddressSpace.AddressPrefixes; ps != nil { + prefs = ps + } + d.Set("address_space", prefs) + + return nil +} + +// resourceArmLocalNetworkGatewayDelete deletes the specified ARM local network gateway. +func resourceArmLocalNetworkGatewayDelete(d *schema.ResourceData, meta interface{}) error { + lnetClient := meta.(*ArmClient).localNetConnClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + name := id.Path["localNetworkGateways"] + resGroup := id.ResourceGroup + + _, err = lnetClient.Delete(resGroup, name, make(chan struct{})) + if err != nil { + return fmt.Errorf("Error issuing Azure ARM delete request of local network gateway '%s': %s", name, err) + } + + return nil +} diff --git a/builtin/providers/azurerm/resource_arm_local_network_gateway_test.go b/builtin/providers/azurerm/resource_arm_local_network_gateway_test.go index 55b9e1e62499..1b57fc9068f4 100644 --- a/builtin/providers/azurerm/resource_arm_local_network_gateway_test.go +++ b/builtin/providers/azurerm/resource_arm_local_network_gateway_test.go @@ -1,108 +1,108 @@ package azurerm -//import ( -// "fmt" -// "testing" -// -// "github.com/Azure/azure-sdk-for-go/core/http" -// "github.com/hashicorp/terraform/helper/resource" -// "github.com/hashicorp/terraform/terraform" -//) -// -//func TestAccAzureRMLocalNetworkGateway_basic(t *testing.T) { -// name := "azurerm_local_network_gateway.test" -// -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// Providers: testAccProviders, -// CheckDestroy: testCheckAzureRMLocalNetworkGatewayDestroy, -// Steps: []resource.TestStep{ -// resource.TestStep{ -// Config: testAccAzureRMLocalNetworkGatewayConfig_basic, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMLocalNetworkGatewayExists(name), -// resource.TestCheckResourceAttr(name, "gateway_address", "127.0.0.1"), -// resource.TestCheckResourceAttr(name, "address_space.0", "127.0.0.0/8"), -// ), -// }, -// }, -// }) -//} -// -//// testCheckAzureRMLocalNetworkGatewayExists returns the resurce.TestCheckFunc -//// which checks whether or not the expected local network gateway exists both -//// in the schema, and on Azure. -//func testCheckAzureRMLocalNetworkGatewayExists(name string) resource.TestCheckFunc { -// return func(s *terraform.State) error { -// // first check within the schema for the local network gateway: -// res, ok := s.RootModule().Resources[name] -// if !ok { -// return fmt.Errorf("Local network gateway '%s' not found.", name) -// } -// -// // then, extract the name and the resource group: -// id, err := parseAzureResourceID(res.Primary.ID) -// if err != nil { -// return err -// } -// localNetName := id.Path["localNetworkGateways"] -// resGrp := id.ResourceGroup -// -// // and finally, check that it exists on Azure: -// lnetClient := testAccProvider.Meta().(*ArmClient).localNetConnClient -// -// resp, err := lnetClient.Get(resGrp, localNetName) -// if err != nil { -// if resp.StatusCode == http.StatusNotFound { -// return fmt.Errorf("Local network gateway '%s' (resource group '%s') does not exist on Azure.", localNetName, resGrp) -// } -// -// return fmt.Errorf("Error reading the state of local network gateway '%s'.", localNetName) -// } -// -// return nil -// } -//} -// -//func testCheckAzureRMLocalNetworkGatewayDestroy(s *terraform.State) error { -// for _, res := range s.RootModule().Resources { -// if res.Type != "azurerm_local_network_gateway" { -// continue -// } -// -// id, err := parseAzureResourceID(res.Primary.ID) -// if err != nil { -// return err -// } -// localNetName := id.Path["localNetworkGateways"] -// resGrp := id.ResourceGroup -// -// lnetClient := testAccProvider.Meta().(*ArmClient).localNetConnClient -// resp, err := lnetClient.Get(resGrp, localNetName) -// -// if err != nil { -// return nil -// } -// -// if resp.StatusCode != http.StatusNotFound { -// return fmt.Errorf("Local network gateway still exists:\n%#v", resp.Properties) -// } -// } -// -// return nil -//} -// -//var testAccAzureRMLocalNetworkGatewayConfig_basic = ` -//resource "azurerm_resource_group" "test" { -// name = "tftestingResourceGroup" -// location = "West US" -//} -// -//resource "azurerm_local_network_gateway" "test" { -// name = "tftestingLocalNetworkGateway" -// location = "${azurerm_resource_group.test.location}" -// resource_group_name = "${azurerm_resource_group.test.name}" -// gateway_address = "127.0.0.1" -// address_space = ["127.0.0.0/8"] -//} -//` +import ( + "fmt" + "testing" + + "github.com/Azure/azure-sdk-for-go/core/http" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAzureRMLocalNetworkGateway_basic(t *testing.T) { + name := "azurerm_local_network_gateway.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMLocalNetworkGatewayDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMLocalNetworkGatewayConfig_basic, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMLocalNetworkGatewayExists(name), + resource.TestCheckResourceAttr(name, "gateway_address", "127.0.0.1"), + resource.TestCheckResourceAttr(name, "address_space.0", "127.0.0.0/8"), + ), + }, + }, + }) +} + +// testCheckAzureRMLocalNetworkGatewayExists returns the resurce.TestCheckFunc +// which checks whether or not the expected local network gateway exists both +// in the schema, and on Azure. +func testCheckAzureRMLocalNetworkGatewayExists(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + // first check within the schema for the local network gateway: + res, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Local network gateway '%s' not found.", name) + } + + // then, extract the name and the resource group: + id, err := parseAzureResourceID(res.Primary.ID) + if err != nil { + return err + } + localNetName := id.Path["localNetworkGateways"] + resGrp := id.ResourceGroup + + // and finally, check that it exists on Azure: + lnetClient := testAccProvider.Meta().(*ArmClient).localNetConnClient + + resp, err := lnetClient.Get(resGrp, localNetName) + if err != nil { + if resp.StatusCode == http.StatusNotFound { + return fmt.Errorf("Local network gateway '%s' (resource group '%s') does not exist on Azure.", localNetName, resGrp) + } + + return fmt.Errorf("Error reading the state of local network gateway '%s'.", localNetName) + } + + return nil + } +} + +func testCheckAzureRMLocalNetworkGatewayDestroy(s *terraform.State) error { + for _, res := range s.RootModule().Resources { + if res.Type != "azurerm_local_network_gateway" { + continue + } + + id, err := parseAzureResourceID(res.Primary.ID) + if err != nil { + return err + } + localNetName := id.Path["localNetworkGateways"] + resGrp := id.ResourceGroup + + lnetClient := testAccProvider.Meta().(*ArmClient).localNetConnClient + resp, err := lnetClient.Get(resGrp, localNetName) + + if err != nil { + return nil + } + + if resp.StatusCode != http.StatusNotFound { + return fmt.Errorf("Local network gateway still exists:\n%#v", resp.Properties) + } + } + + return nil +} + +var testAccAzureRMLocalNetworkGatewayConfig_basic = ` +resource "azurerm_resource_group" "test" { + name = "tftestingResourceGroup" + location = "West US" +} + +resource "azurerm_local_network_gateway" "test" { + name = "tftestingLocalNetworkGateway" + location = "${azurerm_resource_group.test.location}" + resource_group_name = "${azurerm_resource_group.test.name}" + gateway_address = "127.0.0.1" + address_space = ["127.0.0.0/8"] +} +` From 2f66747e79e0f34b3b8cdfcf5baea0e1dd65d65d Mon Sep 17 00:00:00 2001 From: James Nugent Date: Wed, 1 Jun 2016 19:14:40 -0500 Subject: [PATCH 12/17] provider/azurerm: Fix azurerm_network_security_group ``` HTTP_PROXY=http://localhost:8888 make testacc TEST=./builtin/providers/azurerm TESTARGS="-run TestAccAzureRMNetworkSecurityGroup_" ==> Checking that code complies with gofmt requirements... /Users/James/Code/go/bin/stringer go generate $(go list ./... | grep -v /vendor/) 2016/06/01 19:09:36 Generated command/internal_plugin_list.go TF_ACC=1 go test ./builtin/providers/azurerm -v -run TestAccAzureRMNetworkSecurityGroup_ -timeout 120m === RUN TestAccAzureRMNetworkSecurityGroup_basic --- PASS: TestAccAzureRMNetworkSecurityGroup_basic (81.00s) === RUN TestAccAzureRMNetworkSecurityGroup_withTags --- PASS: TestAccAzureRMNetworkSecurityGroup_withTags (101.89s) === RUN TestAccAzureRMNetworkSecurityGroup_addingExtraRules --- PASS: TestAccAzureRMNetworkSecurityGroup_addingExtraRules (99.33s) PASS ok github.com/hashicorp/terraform/builtin/providers/azurerm 282.240s ``` --- builtin/providers/azurerm/provider.go | 6 +- .../resource_arm_network_security_group.go | 581 +++++++++--------- ...esource_arm_network_security_group_test.go | 523 ++++++++-------- 3 files changed, 545 insertions(+), 565 deletions(-) diff --git a/builtin/providers/azurerm/provider.go b/builtin/providers/azurerm/provider.go index f660155e9d01..fb1eb246cdf6 100644 --- a/builtin/providers/azurerm/provider.go +++ b/builtin/providers/azurerm/provider.go @@ -48,9 +48,9 @@ func Provider() terraform.ResourceProvider { "azurerm_availability_set": resourceArmAvailabilitySet(), //"azurerm_cdn_endpoint": resourceArmCdnEndpoint(), //"azurerm_cdn_profile": resourceArmCdnProfile(), - "azurerm_local_network_gateway": resourceArmLocalNetworkGateway(), - "azurerm_network_interface": resourceArmNetworkInterface(), - //"azurerm_network_security_group": resourceArmNetworkSecurityGroup(), + "azurerm_local_network_gateway": resourceArmLocalNetworkGateway(), + "azurerm_network_interface": resourceArmNetworkInterface(), + "azurerm_network_security_group": resourceArmNetworkSecurityGroup(), //"azurerm_network_security_rule": resourceArmNetworkSecurityRule(), "azurerm_public_ip": resourceArmPublicIp(), "azurerm_route": resourceArmRoute(), diff --git a/builtin/providers/azurerm/resource_arm_network_security_group.go b/builtin/providers/azurerm/resource_arm_network_security_group.go index 4d9569c41273..a60df46296da 100644 --- a/builtin/providers/azurerm/resource_arm_network_security_group.go +++ b/builtin/providers/azurerm/resource_arm_network_security_group.go @@ -1,301 +1,284 @@ package azurerm -//import ( -// "bytes" -// "fmt" -// "log" -// "net/http" -// "time" -// -// "github.com/Azure/azure-sdk-for-go/arm/network" -// "github.com/hashicorp/terraform/helper/hashcode" -// "github.com/hashicorp/terraform/helper/resource" -// "github.com/hashicorp/terraform/helper/schema" -//) -// -//func resourceArmNetworkSecurityGroup() *schema.Resource { -// return &schema.Resource{ -// Create: resourceArmNetworkSecurityGroupCreate, -// Read: resourceArmNetworkSecurityGroupRead, -// Update: resourceArmNetworkSecurityGroupCreate, -// Delete: resourceArmNetworkSecurityGroupDelete, -// -// Schema: map[string]*schema.Schema{ -// "name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// }, -// -// "location": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// StateFunc: azureRMNormalizeLocation, -// }, -// -// "resource_group_name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// }, -// -// "security_rule": &schema.Schema{ -// Type: schema.TypeSet, -// Optional: true, -// Computed: true, -// Elem: &schema.Resource{ -// Schema: map[string]*schema.Schema{ -// "name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "description": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { -// value := v.(string) -// if len(value) > 140 { -// errors = append(errors, fmt.Errorf( -// "The network security rule description can be no longer than 140 chars")) -// } -// return -// }, -// }, -// -// "protocol": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ValidateFunc: validateNetworkSecurityRuleProtocol, -// }, -// -// "source_port_range": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "destination_port_range": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "source_address_prefix": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "destination_address_prefix": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "access": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ValidateFunc: validateNetworkSecurityRuleAccess, -// }, -// -// "priority": &schema.Schema{ -// Type: schema.TypeInt, -// Required: true, -// ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { -// value := v.(int) -// if value < 100 || value > 4096 { -// errors = append(errors, fmt.Errorf( -// "The `priority` can only be between 100 and 4096")) -// } -// return -// }, -// }, -// -// "direction": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ValidateFunc: validateNetworkSecurityRuleDirection, -// }, -// }, -// }, -// Set: resourceArmNetworkSecurityGroupRuleHash, -// }, -// -// "tags": tagsSchema(), -// }, -// } -//} -// -//func resourceArmNetworkSecurityGroupCreate(d *schema.ResourceData, meta interface{}) error { -// client := meta.(*ArmClient) -// secClient := client.secGroupClient -// -// name := d.Get("name").(string) -// location := d.Get("location").(string) -// resGroup := d.Get("resource_group_name").(string) -// tags := d.Get("tags").(map[string]interface{}) -// -// sgRules, sgErr := expandAzureRmSecurityRules(d) -// if sgErr != nil { -// return fmt.Errorf("Error Building list of Network Security Group Rules: %s", sgErr) -// } -// -// sg := network.SecurityGroup{ -// Name: &name, -// Location: &location, -// Properties: &network.SecurityGroupPropertiesFormat{ -// SecurityRules: &sgRules, -// }, -// Tags: expandTags(tags), -// } -// -// resp, err := secClient.CreateOrUpdate(resGroup, name, sg) -// if err != nil { -// return err -// } -// -// d.SetId(*resp.ID) -// -// log.Printf("[DEBUG] Waiting for Network Security Group (%s) to become available", name) -// stateConf := &resource.StateChangeConf{ -// Pending: []string{"Accepted", "Updating"}, -// Target: []string{"Succeeded"}, -// Refresh: securityGroupStateRefreshFunc(client, resGroup, name), -// Timeout: 10 * time.Minute, -// } -// if _, err := stateConf.WaitForState(); err != nil { -// return fmt.Errorf("Error waiting for Network Securty Group (%s) to become available: %s", name, err) -// } -// -// return resourceArmNetworkSecurityGroupRead(d, meta) -//} -// -//func resourceArmNetworkSecurityGroupRead(d *schema.ResourceData, meta interface{}) error { -// secGroupClient := meta.(*ArmClient).secGroupClient -// -// id, err := parseAzureResourceID(d.Id()) -// if err != nil { -// return err -// } -// resGroup := id.ResourceGroup -// name := id.Path["networkSecurityGroups"] -// -// resp, err := secGroupClient.Get(resGroup, name, "") -// if resp.StatusCode == http.StatusNotFound { -// d.SetId("") -// return nil -// } -// if err != nil { -// return fmt.Errorf("Error making Read request on Azure Network Security Group %s: %s", name, err) -// } -// -// if resp.Properties.SecurityRules != nil { -// d.Set("security_rule", flattenNetworkSecurityRules(resp.Properties.SecurityRules)) -// } -// -// flattenAndSetTags(d, resp.Tags) -// -// return nil -//} -// -//func resourceArmNetworkSecurityGroupDelete(d *schema.ResourceData, meta interface{}) error { -// secGroupClient := meta.(*ArmClient).secGroupClient -// -// id, err := parseAzureResourceID(d.Id()) -// if err != nil { -// return err -// } -// resGroup := id.ResourceGroup -// name := id.Path["networkSecurityGroups"] -// -// _, err = secGroupClient.Delete(resGroup, name) -// -// return err -//} -// -//func resourceArmNetworkSecurityGroupRuleHash(v interface{}) int { -// var buf bytes.Buffer -// m := v.(map[string]interface{}) -// buf.WriteString(fmt.Sprintf("%s-", m["protocol"].(string))) -// buf.WriteString(fmt.Sprintf("%s-", m["source_port_range"].(string))) -// buf.WriteString(fmt.Sprintf("%s-", m["destination_port_range"].(string))) -// buf.WriteString(fmt.Sprintf("%s-", m["source_address_prefix"].(string))) -// buf.WriteString(fmt.Sprintf("%s-", m["destination_address_prefix"].(string))) -// buf.WriteString(fmt.Sprintf("%s-", m["access"].(string))) -// buf.WriteString(fmt.Sprintf("%d-", m["priority"].(int))) -// buf.WriteString(fmt.Sprintf("%s-", m["direction"].(string))) -// -// return hashcode.String(buf.String()) -//} -// -//func securityGroupStateRefreshFunc(client *ArmClient, resourceGroupName string, securityGroupName string) resource.StateRefreshFunc { -// return func() (interface{}, string, error) { -// res, err := client.secGroupClient.Get(resourceGroupName, securityGroupName, "") -// if err != nil { -// return nil, "", fmt.Errorf("Error issuing read request in securityGroupStateRefreshFunc to Azure ARM for network security group '%s' (RG: '%s'): %s", securityGroupName, resourceGroupName, err) -// } -// -// return res, *res.Properties.ProvisioningState, nil -// } -//} -// -//func flattenNetworkSecurityRules(rules *[]network.SecurityRule) []map[string]interface{} { -// result := make([]map[string]interface{}, 0, len(*rules)) -// for _, rule := range *rules { -// sgRule := make(map[string]interface{}) -// sgRule["name"] = *rule.Name -// sgRule["destination_address_prefix"] = *rule.Properties.DestinationAddressPrefix -// sgRule["destination_port_range"] = *rule.Properties.DestinationPortRange -// sgRule["source_address_prefix"] = *rule.Properties.SourceAddressPrefix -// sgRule["source_port_range"] = *rule.Properties.SourcePortRange -// sgRule["priority"] = int(*rule.Properties.Priority) -// sgRule["access"] = rule.Properties.Access -// sgRule["direction"] = rule.Properties.Direction -// sgRule["protocol"] = rule.Properties.Protocol -// -// if rule.Properties.Description != nil { -// sgRule["description"] = *rule.Properties.Description -// } -// -// result = append(result, sgRule) -// } -// return result -//} -// -//func expandAzureRmSecurityRules(d *schema.ResourceData) ([]network.SecurityRule, error) { -// sgRules := d.Get("security_rule").(*schema.Set).List() -// rules := make([]network.SecurityRule, 0, len(sgRules)) -// -// for _, sgRaw := range sgRules { -// data := sgRaw.(map[string]interface{}) -// -// source_port_range := data["source_port_range"].(string) -// destination_port_range := data["destination_port_range"].(string) -// source_address_prefix := data["source_address_prefix"].(string) -// destination_address_prefix := data["destination_address_prefix"].(string) -// priority := data["priority"].(int) -// -// properties := network.SecurityRulePropertiesFormat{ -// SourcePortRange: &source_port_range, -// DestinationPortRange: &destination_port_range, -// SourceAddressPrefix: &source_address_prefix, -// DestinationAddressPrefix: &destination_address_prefix, -// Priority: &priority, -// Access: network.SecurityRuleAccess(data["access"].(string)), -// Direction: network.SecurityRuleDirection(data["direction"].(string)), -// Protocol: network.SecurityRuleProtocol(data["protocol"].(string)), -// } -// -// if v := data["description"].(string); v != "" { -// properties.Description = &v -// } -// -// name := data["name"].(string) -// rule := network.SecurityRule{ -// Name: &name, -// Properties: &properties, -// } -// -// rules = append(rules, rule) -// } -// -// return rules, nil -//} +import ( + "bytes" + "fmt" + "net/http" + + "github.com/Azure/azure-sdk-for-go/arm/network" + "github.com/hashicorp/terraform/helper/hashcode" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceArmNetworkSecurityGroup() *schema.Resource { + return &schema.Resource{ + Create: resourceArmNetworkSecurityGroupCreate, + Read: resourceArmNetworkSecurityGroupRead, + Update: resourceArmNetworkSecurityGroupCreate, + Delete: resourceArmNetworkSecurityGroupDelete, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "location": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + StateFunc: azureRMNormalizeLocation, + }, + + "resource_group_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "security_rule": { + Type: schema.TypeSet, + Optional: true, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + }, + + "description": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + if len(value) > 140 { + errors = append(errors, fmt.Errorf( + "The network security rule description can be no longer than 140 chars")) + } + return + }, + }, + + "protocol": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validateNetworkSecurityRuleProtocol, + }, + + "source_port_range": { + Type: schema.TypeString, + Required: true, + }, + + "destination_port_range": { + Type: schema.TypeString, + Required: true, + }, + + "source_address_prefix": { + Type: schema.TypeString, + Required: true, + }, + + "destination_address_prefix": { + Type: schema.TypeString, + Required: true, + }, + + "access": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validateNetworkSecurityRuleAccess, + }, + + "priority": { + Type: schema.TypeInt, + Required: true, + ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { + value := v.(int) + if value < 100 || value > 4096 { + errors = append(errors, fmt.Errorf( + "The `priority` can only be between 100 and 4096")) + } + return + }, + }, + + "direction": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validateNetworkSecurityRuleDirection, + }, + }, + }, + Set: resourceArmNetworkSecurityGroupRuleHash, + }, + + "tags": tagsSchema(), + }, + } +} + +func resourceArmNetworkSecurityGroupCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient) + secClient := client.secGroupClient + + name := d.Get("name").(string) + location := d.Get("location").(string) + resGroup := d.Get("resource_group_name").(string) + tags := d.Get("tags").(map[string]interface{}) + + sgRules, sgErr := expandAzureRmSecurityRules(d) + if sgErr != nil { + return fmt.Errorf("Error Building list of Network Security Group Rules: %s", sgErr) + } + + sg := network.SecurityGroup{ + Name: &name, + Location: &location, + Properties: &network.SecurityGroupPropertiesFormat{ + SecurityRules: &sgRules, + }, + Tags: expandTags(tags), + } + + _, err := secClient.CreateOrUpdate(resGroup, name, sg, make(chan struct{})) + if err != nil { + return err + } + + read, err := secClient.Get(resGroup, name, "") + if err != nil { + return err + } + if read.ID == nil { + return fmt.Errorf("Cannot read Virtual Network %s (resource group %s) ID", name, resGroup) + } + + d.SetId(*read.ID) + + return resourceArmNetworkSecurityGroupRead(d, meta) +} + +func resourceArmNetworkSecurityGroupRead(d *schema.ResourceData, meta interface{}) error { + secGroupClient := meta.(*ArmClient).secGroupClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + name := id.Path["networkSecurityGroups"] + + resp, err := secGroupClient.Get(resGroup, name, "") + if resp.StatusCode == http.StatusNotFound { + d.SetId("") + return nil + } + if err != nil { + return fmt.Errorf("Error making Read request on Azure Network Security Group %s: %s", name, err) + } + + if resp.Properties.SecurityRules != nil { + d.Set("security_rule", flattenNetworkSecurityRules(resp.Properties.SecurityRules)) + } + + flattenAndSetTags(d, resp.Tags) + + return nil +} + +func resourceArmNetworkSecurityGroupDelete(d *schema.ResourceData, meta interface{}) error { + secGroupClient := meta.(*ArmClient).secGroupClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + name := id.Path["networkSecurityGroups"] + + _, err = secGroupClient.Delete(resGroup, name, make(chan struct{})) + + return err +} + +func resourceArmNetworkSecurityGroupRuleHash(v interface{}) int { + var buf bytes.Buffer + m := v.(map[string]interface{}) + buf.WriteString(fmt.Sprintf("%s-", m["protocol"].(string))) + buf.WriteString(fmt.Sprintf("%s-", m["source_port_range"].(string))) + buf.WriteString(fmt.Sprintf("%s-", m["destination_port_range"].(string))) + buf.WriteString(fmt.Sprintf("%s-", m["source_address_prefix"].(string))) + buf.WriteString(fmt.Sprintf("%s-", m["destination_address_prefix"].(string))) + buf.WriteString(fmt.Sprintf("%s-", m["access"].(string))) + buf.WriteString(fmt.Sprintf("%d-", m["priority"].(int))) + buf.WriteString(fmt.Sprintf("%s-", m["direction"].(string))) + + return hashcode.String(buf.String()) +} + +func flattenNetworkSecurityRules(rules *[]network.SecurityRule) []map[string]interface{} { + result := make([]map[string]interface{}, 0, len(*rules)) + for _, rule := range *rules { + sgRule := make(map[string]interface{}) + sgRule["name"] = *rule.Name + sgRule["destination_address_prefix"] = *rule.Properties.DestinationAddressPrefix + sgRule["destination_port_range"] = *rule.Properties.DestinationPortRange + sgRule["source_address_prefix"] = *rule.Properties.SourceAddressPrefix + sgRule["source_port_range"] = *rule.Properties.SourcePortRange + sgRule["priority"] = int(*rule.Properties.Priority) + sgRule["access"] = rule.Properties.Access + sgRule["direction"] = rule.Properties.Direction + sgRule["protocol"] = rule.Properties.Protocol + + if rule.Properties.Description != nil { + sgRule["description"] = *rule.Properties.Description + } + + result = append(result, sgRule) + } + return result +} + +func expandAzureRmSecurityRules(d *schema.ResourceData) ([]network.SecurityRule, error) { + sgRules := d.Get("security_rule").(*schema.Set).List() + rules := make([]network.SecurityRule, 0, len(sgRules)) + + for _, sgRaw := range sgRules { + data := sgRaw.(map[string]interface{}) + + source_port_range := data["source_port_range"].(string) + destination_port_range := data["destination_port_range"].(string) + source_address_prefix := data["source_address_prefix"].(string) + destination_address_prefix := data["destination_address_prefix"].(string) + priority := int32(data["priority"].(int)) + + properties := network.SecurityRulePropertiesFormat{ + SourcePortRange: &source_port_range, + DestinationPortRange: &destination_port_range, + SourceAddressPrefix: &source_address_prefix, + DestinationAddressPrefix: &destination_address_prefix, + Priority: &priority, + Access: network.SecurityRuleAccess(data["access"].(string)), + Direction: network.SecurityRuleDirection(data["direction"].(string)), + Protocol: network.SecurityRuleProtocol(data["protocol"].(string)), + } + + if v := data["description"].(string); v != "" { + properties.Description = &v + } + + name := data["name"].(string) + rule := network.SecurityRule{ + Name: &name, + Properties: &properties, + } + + rules = append(rules, rule) + } + + return rules, nil +} diff --git a/builtin/providers/azurerm/resource_arm_network_security_group_test.go b/builtin/providers/azurerm/resource_arm_network_security_group_test.go index d05ff88bf094..44e8eeb2cf13 100644 --- a/builtin/providers/azurerm/resource_arm_network_security_group_test.go +++ b/builtin/providers/azurerm/resource_arm_network_security_group_test.go @@ -1,265 +1,262 @@ package azurerm -//import ( -// "fmt" -// "net/http" -// "testing" -// -// "github.com/hashicorp/terraform/helper/resource" -// "github.com/hashicorp/terraform/terraform" -//) -// -//func TestAccAzureRMNetworkSecurityGroup_basic(t *testing.T) { -// -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// Providers: testAccProviders, -// CheckDestroy: testCheckAzureRMNetworkSecurityGroupDestroy, -// Steps: []resource.TestStep{ -// resource.TestStep{ -// Config: testAccAzureRMNetworkSecurityGroup_basic, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMNetworkSecurityGroupExists("azurerm_network_security_group.test"), -// ), -// }, -// }, -// }) -//} -// -//func TestAccAzureRMNetworkSecurityGroup_withTags(t *testing.T) { -// -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// Providers: testAccProviders, -// CheckDestroy: testCheckAzureRMNetworkSecurityGroupDestroy, -// Steps: []resource.TestStep{ -// resource.TestStep{ -// Config: testAccAzureRMNetworkSecurityGroup_withTags, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMNetworkSecurityGroupExists("azurerm_network_security_group.test"), -// resource.TestCheckResourceAttr( -// "azurerm_network_security_group.test", "tags.#", "2"), -// resource.TestCheckResourceAttr( -// "azurerm_network_security_group.test", "tags.environment", "Production"), -// resource.TestCheckResourceAttr( -// "azurerm_network_security_group.test", "tags.cost_center", "MSFT"), -// ), -// }, -// -// resource.TestStep{ -// Config: testAccAzureRMNetworkSecurityGroup_withTagsUpdate, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMNetworkSecurityGroupExists("azurerm_network_security_group.test"), -// resource.TestCheckResourceAttr( -// "azurerm_network_security_group.test", "tags.#", "1"), -// resource.TestCheckResourceAttr( -// "azurerm_network_security_group.test", "tags.environment", "staging"), -// ), -// }, -// }, -// }) -//} -// -//func TestAccAzureRMNetworkSecurityGroup_addingExtraRules(t *testing.T) { -// -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// Providers: testAccProviders, -// CheckDestroy: testCheckAzureRMNetworkSecurityGroupDestroy, -// Steps: []resource.TestStep{ -// resource.TestStep{ -// Config: testAccAzureRMNetworkSecurityGroup_basic, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMNetworkSecurityGroupExists("azurerm_network_security_group.test"), -// resource.TestCheckResourceAttr( -// "azurerm_network_security_group.test", "security_rule.#", "1"), -// ), -// }, -// -// resource.TestStep{ -// Config: testAccAzureRMNetworkSecurityGroup_anotherRule, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMNetworkSecurityGroupExists("azurerm_network_security_group.test"), -// resource.TestCheckResourceAttr( -// "azurerm_network_security_group.test", "security_rule.#", "2"), -// ), -// }, -// }, -// }) -//} -// -//func testCheckAzureRMNetworkSecurityGroupExists(name string) resource.TestCheckFunc { -// return func(s *terraform.State) error { -// -// rs, ok := s.RootModule().Resources[name] -// if !ok { -// return fmt.Errorf("Not found: %s", name) -// } -// -// sgName := rs.Primary.Attributes["name"] -// resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] -// if !hasResourceGroup { -// return fmt.Errorf("Bad: no resource group found in state for network security group: %s", sgName) -// } -// -// conn := testAccProvider.Meta().(*ArmClient).secGroupClient -// -// resp, err := conn.Get(resourceGroup, sgName, "") -// if err != nil { -// return fmt.Errorf("Bad: Get on secGroupClient: %s", err) -// } -// -// if resp.StatusCode == http.StatusNotFound { -// return fmt.Errorf("Bad: Network Security Group %q (resource group: %q) does not exist", name, resourceGroup) -// } -// -// return nil -// } -//} -// -//func testCheckAzureRMNetworkSecurityGroupDestroy(s *terraform.State) error { -// conn := testAccProvider.Meta().(*ArmClient).secGroupClient -// -// for _, rs := range s.RootModule().Resources { -// if rs.Type != "azurerm_network_security_group" { -// continue -// } -// -// name := rs.Primary.Attributes["name"] -// resourceGroup := rs.Primary.Attributes["resource_group_name"] -// -// resp, err := conn.Get(resourceGroup, name, "") -// -// if err != nil { -// return nil -// } -// -// if resp.StatusCode != http.StatusNotFound { -// return fmt.Errorf("Network Security Group still exists:\n%#v", resp.Properties) -// } -// } -// -// return nil -//} -// -//var testAccAzureRMNetworkSecurityGroup_basic = ` -//resource "azurerm_resource_group" "test" { -// name = "acceptanceTestResourceGroup1" -// location = "West US" -//} -// -//resource "azurerm_network_security_group" "test" { -// name = "acceptanceTestSecurityGroup1" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// -// security_rule { -// name = "test123" -// priority = 100 -// direction = "Inbound" -// access = "Allow" -// protocol = "Tcp" -// source_port_range = "*" -// destination_port_range = "*" -// source_address_prefix = "*" -// destination_address_prefix = "*" -// } -//} -//` -// -//var testAccAzureRMNetworkSecurityGroup_anotherRule = ` -//resource "azurerm_resource_group" "test" { -// name = "acceptanceTestResourceGroup1" -// location = "West US" -//} -// -//resource "azurerm_network_security_group" "test" { -// name = "acceptanceTestSecurityGroup1" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// -// security_rule { -// name = "test123" -// priority = 100 -// direction = "Inbound" -// access = "Allow" -// protocol = "Tcp" -// source_port_range = "*" -// destination_port_range = "*" -// source_address_prefix = "*" -// destination_address_prefix = "*" -// } -// -// security_rule { -// name = "testDeny" -// priority = 101 -// direction = "Inbound" -// access = "Deny" -// protocol = "Udp" -// source_port_range = "*" -// destination_port_range = "*" -// source_address_prefix = "*" -// destination_address_prefix = "*" -// } -//} -//` -// -//var testAccAzureRMNetworkSecurityGroup_withTags = ` -//resource "azurerm_resource_group" "test" { -// name = "acceptanceTestResourceGroup1" -// location = "West US" -//} -// -//resource "azurerm_network_security_group" "test" { -// name = "acceptanceTestSecurityGroup1" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// -// security_rule { -// name = "test123" -// priority = 100 -// direction = "Inbound" -// access = "Allow" -// protocol = "Tcp" -// source_port_range = "*" -// destination_port_range = "*" -// source_address_prefix = "*" -// destination_address_prefix = "*" -// } -// -// -// tags { -// environment = "Production" -// cost_center = "MSFT" -// } -//} -//` -// -//var testAccAzureRMNetworkSecurityGroup_withTagsUpdate = ` -//resource "azurerm_resource_group" "test" { -// name = "acceptanceTestResourceGroup1" -// location = "West US" -//} -// -//resource "azurerm_network_security_group" "test" { -// name = "acceptanceTestSecurityGroup1" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// -// security_rule { -// name = "test123" -// priority = 100 -// direction = "Inbound" -// access = "Allow" -// protocol = "Tcp" -// source_port_range = "*" -// destination_port_range = "*" -// source_address_prefix = "*" -// destination_address_prefix = "*" -// } -// -// tags { -// environment = "staging" -// } -//} -//` +import ( + "fmt" + "net/http" + "testing" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAzureRMNetworkSecurityGroup_basic(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMNetworkSecurityGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMNetworkSecurityGroup_basic, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMNetworkSecurityGroupExists("azurerm_network_security_group.test"), + ), + }, + }, + }) +} + +func TestAccAzureRMNetworkSecurityGroup_withTags(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMNetworkSecurityGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMNetworkSecurityGroup_withTags, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMNetworkSecurityGroupExists("azurerm_network_security_group.test"), + resource.TestCheckResourceAttr( + "azurerm_network_security_group.test", "tags.#", "2"), + resource.TestCheckResourceAttr( + "azurerm_network_security_group.test", "tags.environment", "Production"), + resource.TestCheckResourceAttr( + "azurerm_network_security_group.test", "tags.cost_center", "MSFT"), + ), + }, + + { + Config: testAccAzureRMNetworkSecurityGroup_withTagsUpdate, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMNetworkSecurityGroupExists("azurerm_network_security_group.test"), + resource.TestCheckResourceAttr( + "azurerm_network_security_group.test", "tags.#", "1"), + resource.TestCheckResourceAttr( + "azurerm_network_security_group.test", "tags.environment", "staging"), + ), + }, + }, + }) +} + +func TestAccAzureRMNetworkSecurityGroup_addingExtraRules(t *testing.T) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMNetworkSecurityGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMNetworkSecurityGroup_basic, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMNetworkSecurityGroupExists("azurerm_network_security_group.test"), + resource.TestCheckResourceAttr( + "azurerm_network_security_group.test", "security_rule.#", "1"), + ), + }, + + { + Config: testAccAzureRMNetworkSecurityGroup_anotherRule, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMNetworkSecurityGroupExists("azurerm_network_security_group.test"), + resource.TestCheckResourceAttr( + "azurerm_network_security_group.test", "security_rule.#", "2"), + ), + }, + }, + }) +} + +func testCheckAzureRMNetworkSecurityGroupExists(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + sgName := rs.Primary.Attributes["name"] + resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] + if !hasResourceGroup { + return fmt.Errorf("Bad: no resource group found in state for network security group: %s", sgName) + } + + conn := testAccProvider.Meta().(*ArmClient).secGroupClient + + resp, err := conn.Get(resourceGroup, sgName, "") + if err != nil { + return fmt.Errorf("Bad: Get on secGroupClient: %s", err) + } + + if resp.StatusCode == http.StatusNotFound { + return fmt.Errorf("Bad: Network Security Group %q (resource group: %q) does not exist", name, resourceGroup) + } + + return nil + } +} + +func testCheckAzureRMNetworkSecurityGroupDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*ArmClient).secGroupClient + + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_network_security_group" { + continue + } + + name := rs.Primary.Attributes["name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] + + resp, err := conn.Get(resourceGroup, name, "") + + if err != nil { + return nil + } + + if resp.StatusCode != http.StatusNotFound { + return fmt.Errorf("Network Security Group still exists:\n%#v", resp.Properties) + } + } + + return nil +} + +var testAccAzureRMNetworkSecurityGroup_basic = ` +resource "azurerm_resource_group" "test" { + name = "acceptanceTestResourceGroup1" + location = "West US" +} + +resource "azurerm_network_security_group" "test" { + name = "acceptanceTestSecurityGroup1" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + + security_rule { + name = "test123" + priority = 100 + direction = "Inbound" + access = "Allow" + protocol = "Tcp" + source_port_range = "*" + destination_port_range = "*" + source_address_prefix = "*" + destination_address_prefix = "*" + } +} +` + +var testAccAzureRMNetworkSecurityGroup_anotherRule = ` +resource "azurerm_resource_group" "test" { + name = "acceptanceTestResourceGroup1" + location = "West US" +} + +resource "azurerm_network_security_group" "test" { + name = "acceptanceTestSecurityGroup1" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + + security_rule { + name = "test123" + priority = 100 + direction = "Inbound" + access = "Allow" + protocol = "Tcp" + source_port_range = "*" + destination_port_range = "*" + source_address_prefix = "*" + destination_address_prefix = "*" + } + + security_rule { + name = "testDeny" + priority = 101 + direction = "Inbound" + access = "Deny" + protocol = "Udp" + source_port_range = "*" + destination_port_range = "*" + source_address_prefix = "*" + destination_address_prefix = "*" + } +} +` + +var testAccAzureRMNetworkSecurityGroup_withTags = ` +resource "azurerm_resource_group" "test" { + name = "acceptanceTestResourceGroup1" + location = "West US" +} + +resource "azurerm_network_security_group" "test" { + name = "acceptanceTestSecurityGroup1" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + + security_rule { + name = "test123" + priority = 100 + direction = "Inbound" + access = "Allow" + protocol = "Tcp" + source_port_range = "*" + destination_port_range = "*" + source_address_prefix = "*" + destination_address_prefix = "*" + } + + + tags { + environment = "Production" + cost_center = "MSFT" + } +} +` + +var testAccAzureRMNetworkSecurityGroup_withTagsUpdate = ` +resource "azurerm_resource_group" "test" { + name = "acceptanceTestResourceGroup1" + location = "West US" +} + +resource "azurerm_network_security_group" "test" { + name = "acceptanceTestSecurityGroup1" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + + security_rule { + name = "test123" + priority = 100 + direction = "Inbound" + access = "Allow" + protocol = "Tcp" + source_port_range = "*" + destination_port_range = "*" + source_address_prefix = "*" + destination_address_prefix = "*" + } + + tags { + environment = "staging" + } +} +` From 8ecfddf5076530015ce4d6250dd3b3c0ae7caa88 Mon Sep 17 00:00:00 2001 From: James Nugent Date: Wed, 1 Jun 2016 19:25:19 -0500 Subject: [PATCH 13/17] provider/azurerm: Fix azurerm_network_security_group_rule ``` HTTP_PROXY=http://localhost:8888 make testacc TEST=./builtin/providers/azurerm TESTARGS="-run TestAccAzureRMNetworkSecurityRule_" ==> Checking that code complies with gofmt requirements... /Users/James/Code/go/bin/stringer go generate $(go list ./... | grep -v /vendor/) 2016/06/01 19:19:59 Generated command/internal_plugin_list.go TF_ACC=1 go test ./builtin/providers/azurerm -v -run TestAccAzureRMNetworkSecurityRule_ -timeout 120m === RUN TestAccAzureRMNetworkSecurityRule_basic --- PASS: TestAccAzureRMNetworkSecurityRule_basic (105.61s) === RUN TestAccAzureRMNetworkSecurityRule_addingRules --- PASS: TestAccAzureRMNetworkSecurityRule_addingRules (141.59s) PASS ok github.com/hashicorp/terraform/builtin/providers/azurerm 247.221s ``` --- builtin/providers/azurerm/provider.go | 18 +- .../resource_arm_network_security_rule.go | 419 +++++++++--------- ...resource_arm_network_security_rule_test.go | 402 ++++++++--------- 3 files changed, 412 insertions(+), 427 deletions(-) diff --git a/builtin/providers/azurerm/provider.go b/builtin/providers/azurerm/provider.go index fb1eb246cdf6..57ea897d4365 100644 --- a/builtin/providers/azurerm/provider.go +++ b/builtin/providers/azurerm/provider.go @@ -51,15 +51,15 @@ func Provider() terraform.ResourceProvider { "azurerm_local_network_gateway": resourceArmLocalNetworkGateway(), "azurerm_network_interface": resourceArmNetworkInterface(), "azurerm_network_security_group": resourceArmNetworkSecurityGroup(), - //"azurerm_network_security_rule": resourceArmNetworkSecurityRule(), - "azurerm_public_ip": resourceArmPublicIp(), - "azurerm_route": resourceArmRoute(), - "azurerm_route_table": resourceArmRouteTable(), - "azurerm_storage_account": resourceArmStorageAccount(), - "azurerm_storage_blob": resourceArmStorageBlob(), - "azurerm_storage_container": resourceArmStorageContainer(), - "azurerm_storage_queue": resourceArmStorageQueue(), - "azurerm_subnet": resourceArmSubnet(), + "azurerm_network_security_rule": resourceArmNetworkSecurityRule(), + "azurerm_public_ip": resourceArmPublicIp(), + "azurerm_route": resourceArmRoute(), + "azurerm_route_table": resourceArmRouteTable(), + "azurerm_storage_account": resourceArmStorageAccount(), + "azurerm_storage_blob": resourceArmStorageBlob(), + "azurerm_storage_container": resourceArmStorageContainer(), + "azurerm_storage_queue": resourceArmStorageQueue(), + "azurerm_subnet": resourceArmSubnet(), //"azurerm_template_deployment": resourceArmTemplateDeployment(), //"azurerm_virtual_machine": resourceArmVirtualMachine(), "azurerm_virtual_network": resourceArmVirtualNetwork(), diff --git a/builtin/providers/azurerm/resource_arm_network_security_rule.go b/builtin/providers/azurerm/resource_arm_network_security_rule.go index b155fce6fe4b..050781cd3193 100644 --- a/builtin/providers/azurerm/resource_arm_network_security_rule.go +++ b/builtin/providers/azurerm/resource_arm_network_security_rule.go @@ -1,219 +1,204 @@ package azurerm -//import ( -// "fmt" -// "log" -// "net/http" -// "time" -// -// "github.com/Azure/azure-sdk-for-go/arm/network" -// "github.com/hashicorp/terraform/helper/resource" -// "github.com/hashicorp/terraform/helper/schema" -//) -// -//func resourceArmNetworkSecurityRule() *schema.Resource { -// return &schema.Resource{ -// Create: resourceArmNetworkSecurityRuleCreate, -// Read: resourceArmNetworkSecurityRuleRead, -// Update: resourceArmNetworkSecurityRuleCreate, -// Delete: resourceArmNetworkSecurityRuleDelete, -// -// Schema: map[string]*schema.Schema{ -// "name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// }, -// -// "resource_group_name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// }, -// -// "network_security_group_name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "description": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { -// value := v.(string) -// if len(value) > 140 { -// errors = append(errors, fmt.Errorf( -// "The network security rule description can be no longer than 140 chars")) -// } -// return -// }, -// }, -// -// "protocol": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ValidateFunc: validateNetworkSecurityRuleProtocol, -// }, -// -// "source_port_range": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "destination_port_range": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "source_address_prefix": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "destination_address_prefix": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "access": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ValidateFunc: validateNetworkSecurityRuleAccess, -// }, -// -// "priority": &schema.Schema{ -// Type: schema.TypeInt, -// Required: true, -// ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { -// value := v.(int) -// if value < 100 || value > 4096 { -// errors = append(errors, fmt.Errorf( -// "The `priority` can only be between 100 and 4096")) -// } -// return -// }, -// }, -// -// "direction": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ValidateFunc: validateNetworkSecurityRuleDirection, -// }, -// }, -// } -//} -// -//func resourceArmNetworkSecurityRuleCreate(d *schema.ResourceData, meta interface{}) error { -// client := meta.(*ArmClient) -// secClient := client.secRuleClient -// -// name := d.Get("name").(string) -// nsgName := d.Get("network_security_group_name").(string) -// resGroup := d.Get("resource_group_name").(string) -// -// source_port_range := d.Get("source_port_range").(string) -// destination_port_range := d.Get("destination_port_range").(string) -// source_address_prefix := d.Get("source_address_prefix").(string) -// destination_address_prefix := d.Get("destination_address_prefix").(string) -// priority := d.Get("priority").(int) -// access := d.Get("access").(string) -// direction := d.Get("direction").(string) -// protocol := d.Get("protocol").(string) -// -// armMutexKV.Lock(nsgName) -// defer armMutexKV.Unlock(nsgName) -// -// properties := network.SecurityRulePropertiesFormat{ -// SourcePortRange: &source_port_range, -// DestinationPortRange: &destination_port_range, -// SourceAddressPrefix: &source_address_prefix, -// DestinationAddressPrefix: &destination_address_prefix, -// Priority: &priority, -// Access: network.SecurityRuleAccess(access), -// Direction: network.SecurityRuleDirection(direction), -// Protocol: network.SecurityRuleProtocol(protocol), -// } -// -// if v, ok := d.GetOk("description"); ok { -// description := v.(string) -// properties.Description = &description -// } -// -// sgr := network.SecurityRule{ -// Name: &name, -// Properties: &properties, -// } -// -// resp, err := secClient.CreateOrUpdate(resGroup, nsgName, name, sgr) -// if err != nil { -// return err -// } -// d.SetId(*resp.ID) -// -// log.Printf("[DEBUG] Waiting for Network Security Rule (%s) to become available", name) -// stateConf := &resource.StateChangeConf{ -// Pending: []string{"Accepted", "Updating"}, -// Target: []string{"Succeeded"}, -// Refresh: securityRuleStateRefreshFunc(client, resGroup, nsgName, name), -// Timeout: 10 * time.Minute, -// } -// if _, err := stateConf.WaitForState(); err != nil { -// return fmt.Errorf("Error waiting for Network Securty Rule (%s) to become available: %s", name, err) -// } -// -// return resourceArmNetworkSecurityRuleRead(d, meta) -//} -// -//func resourceArmNetworkSecurityRuleRead(d *schema.ResourceData, meta interface{}) error { -// secRuleClient := meta.(*ArmClient).secRuleClient -// -// id, err := parseAzureResourceID(d.Id()) -// if err != nil { -// return err -// } -// resGroup := id.ResourceGroup -// networkSGName := id.Path["networkSecurityGroups"] -// sgRuleName := id.Path["securityRules"] -// -// resp, err := secRuleClient.Get(resGroup, networkSGName, sgRuleName) -// if resp.StatusCode == http.StatusNotFound { -// d.SetId("") -// return nil -// } -// if err != nil { -// return fmt.Errorf("Error making Read request on Azure Network Security Rule %s: %s", sgRuleName, err) -// } -// -// return nil -//} -// -//func resourceArmNetworkSecurityRuleDelete(d *schema.ResourceData, meta interface{}) error { -// client := meta.(*ArmClient) -// secRuleClient := client.secRuleClient -// -// id, err := parseAzureResourceID(d.Id()) -// if err != nil { -// return err -// } -// resGroup := id.ResourceGroup -// nsgName := id.Path["networkSecurityGroups"] -// sgRuleName := id.Path["securityRules"] -// -// armMutexKV.Lock(nsgName) -// defer armMutexKV.Unlock(nsgName) -// -// _, err = secRuleClient.Delete(resGroup, nsgName, sgRuleName) -// -// return err -//} -// -//func securityRuleStateRefreshFunc(client *ArmClient, resourceGroupName string, networkSecurityGroupName string, securityRuleName string) resource.StateRefreshFunc { -// return func() (interface{}, string, error) { -// res, err := client.secRuleClient.Get(resourceGroupName, networkSecurityGroupName, securityRuleName) -// if err != nil { -// return nil, "", fmt.Errorf("Error issuing read request in securityGroupStateRefreshFunc to Azure ARM for network security rule '%s' (RG: '%s') (NSG: '%s'): %s", securityRuleName, resourceGroupName, networkSecurityGroupName, err) -// } -// -// return res, *res.Properties.ProvisioningState, nil -// } -//} +import ( + "fmt" + "net/http" + + "github.com/Azure/azure-sdk-for-go/arm/network" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceArmNetworkSecurityRule() *schema.Resource { + return &schema.Resource{ + Create: resourceArmNetworkSecurityRuleCreate, + Read: resourceArmNetworkSecurityRuleRead, + Update: resourceArmNetworkSecurityRuleCreate, + Delete: resourceArmNetworkSecurityRuleDelete, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "resource_group_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "network_security_group_name": { + Type: schema.TypeString, + Required: true, + }, + + "description": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + if len(value) > 140 { + errors = append(errors, fmt.Errorf( + "The network security rule description can be no longer than 140 chars")) + } + return + }, + }, + + "protocol": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validateNetworkSecurityRuleProtocol, + }, + + "source_port_range": { + Type: schema.TypeString, + Required: true, + }, + + "destination_port_range": { + Type: schema.TypeString, + Required: true, + }, + + "source_address_prefix": { + Type: schema.TypeString, + Required: true, + }, + + "destination_address_prefix": { + Type: schema.TypeString, + Required: true, + }, + + "access": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validateNetworkSecurityRuleAccess, + }, + + "priority": { + Type: schema.TypeInt, + Required: true, + ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { + value := v.(int) + if value < 100 || value > 4096 { + errors = append(errors, fmt.Errorf( + "The `priority` can only be between 100 and 4096")) + } + return + }, + }, + + "direction": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validateNetworkSecurityRuleDirection, + }, + }, + } +} + +func resourceArmNetworkSecurityRuleCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient) + secClient := client.secRuleClient + + name := d.Get("name").(string) + nsgName := d.Get("network_security_group_name").(string) + resGroup := d.Get("resource_group_name").(string) + + source_port_range := d.Get("source_port_range").(string) + destination_port_range := d.Get("destination_port_range").(string) + source_address_prefix := d.Get("source_address_prefix").(string) + destination_address_prefix := d.Get("destination_address_prefix").(string) + priority := int32(d.Get("priority").(int)) + access := d.Get("access").(string) + direction := d.Get("direction").(string) + protocol := d.Get("protocol").(string) + + armMutexKV.Lock(nsgName) + defer armMutexKV.Unlock(nsgName) + + properties := network.SecurityRulePropertiesFormat{ + SourcePortRange: &source_port_range, + DestinationPortRange: &destination_port_range, + SourceAddressPrefix: &source_address_prefix, + DestinationAddressPrefix: &destination_address_prefix, + Priority: &priority, + Access: network.SecurityRuleAccess(access), + Direction: network.SecurityRuleDirection(direction), + Protocol: network.SecurityRuleProtocol(protocol), + } + + if v, ok := d.GetOk("description"); ok { + description := v.(string) + properties.Description = &description + } + + sgr := network.SecurityRule{ + Name: &name, + Properties: &properties, + } + + _, err := secClient.CreateOrUpdate(resGroup, nsgName, name, sgr, make(chan struct{})) + if err != nil { + return err + } + + read, err := secClient.Get(resGroup, nsgName, name) + if err != nil { + return err + } + if read.ID == nil { + return fmt.Errorf("Cannot read Security Group Rule %s/%s (resource group %s) ID", + nsgName, name, resGroup) + } + + d.SetId(*read.ID) + + return resourceArmNetworkSecurityRuleRead(d, meta) +} + +func resourceArmNetworkSecurityRuleRead(d *schema.ResourceData, meta interface{}) error { + secRuleClient := meta.(*ArmClient).secRuleClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + networkSGName := id.Path["networkSecurityGroups"] + sgRuleName := id.Path["securityRules"] + + resp, err := secRuleClient.Get(resGroup, networkSGName, sgRuleName) + if resp.StatusCode == http.StatusNotFound { + d.SetId("") + return nil + } + if err != nil { + return fmt.Errorf("Error making Read request on Azure Network Security Rule %s: %s", sgRuleName, err) + } + + return nil +} + +func resourceArmNetworkSecurityRuleDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient) + secRuleClient := client.secRuleClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + nsgName := id.Path["networkSecurityGroups"] + sgRuleName := id.Path["securityRules"] + + armMutexKV.Lock(nsgName) + defer armMutexKV.Unlock(nsgName) + + _, err = secRuleClient.Delete(resGroup, nsgName, sgRuleName, make(chan struct{})) + + return err +} diff --git a/builtin/providers/azurerm/resource_arm_network_security_rule_test.go b/builtin/providers/azurerm/resource_arm_network_security_rule_test.go index 114911574ed9..6b97486808d6 100644 --- a/builtin/providers/azurerm/resource_arm_network_security_rule_test.go +++ b/builtin/providers/azurerm/resource_arm_network_security_rule_test.go @@ -1,203 +1,203 @@ package azurerm -//import ( -// "fmt" -// "net/http" -// "testing" -// -// "github.com/hashicorp/terraform/helper/resource" -// "github.com/hashicorp/terraform/terraform" -//) -// -//func TestAccAzureRMNetworkSecurityRule_basic(t *testing.T) { -// -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// Providers: testAccProviders, -// CheckDestroy: testCheckAzureRMNetworkSecurityRuleDestroy, -// Steps: []resource.TestStep{ -// resource.TestStep{ -// Config: testAccAzureRMNetworkSecurityRule_basic, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMNetworkSecurityRuleExists("azurerm_network_security_rule.test"), -// ), -// }, -// }, -// }) -//} -// -//func TestAccAzureRMNetworkSecurityRule_addingRules(t *testing.T) { -// -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// Providers: testAccProviders, -// CheckDestroy: testCheckAzureRMNetworkSecurityRuleDestroy, -// Steps: []resource.TestStep{ -// resource.TestStep{ -// Config: testAccAzureRMNetworkSecurityRule_updateBasic, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMNetworkSecurityRuleExists("azurerm_network_security_rule.test1"), -// ), -// }, -// -// resource.TestStep{ -// Config: testAccAzureRMNetworkSecurityRule_updateExtraRule, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMNetworkSecurityRuleExists("azurerm_network_security_rule.test2"), -// ), -// }, -// }, -// }) -//} -// -//func testCheckAzureRMNetworkSecurityRuleExists(name string) resource.TestCheckFunc { -// return func(s *terraform.State) error { -// -// rs, ok := s.RootModule().Resources[name] -// if !ok { -// return fmt.Errorf("Not found: %s", name) -// } -// -// sgName := rs.Primary.Attributes["network_security_group_name"] -// sgrName := rs.Primary.Attributes["name"] -// resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] -// if !hasResourceGroup { -// return fmt.Errorf("Bad: no resource group found in state for network security rule: %s", sgName) -// } -// -// conn := testAccProvider.Meta().(*ArmClient).secRuleClient -// -// resp, err := conn.Get(resourceGroup, sgName, sgrName) -// if err != nil { -// return fmt.Errorf("Bad: Get on secRuleClient: %s", err) -// } -// -// if resp.StatusCode == http.StatusNotFound { -// return fmt.Errorf("Bad: Network Security Rule %q (resource group: %q) (network security group: %q) does not exist", sgrName, sgName, resourceGroup) -// } -// -// return nil -// } -//} -// -//func testCheckAzureRMNetworkSecurityRuleDestroy(s *terraform.State) error { -// conn := testAccProvider.Meta().(*ArmClient).secRuleClient -// -// for _, rs := range s.RootModule().Resources { -// -// if rs.Type != "azurerm_network_security_rule" { -// continue -// } -// -// sgName := rs.Primary.Attributes["network_security_group_name"] -// sgrName := rs.Primary.Attributes["name"] -// resourceGroup := rs.Primary.Attributes["resource_group_name"] -// -// resp, err := conn.Get(resourceGroup, sgName, sgrName) -// -// if err != nil { -// return nil -// } -// -// if resp.StatusCode != http.StatusNotFound { -// return fmt.Errorf("Network Security Rule still exists:\n%#v", resp.Properties) -// } -// } -// -// return nil -//} -// -//var testAccAzureRMNetworkSecurityRule_basic = ` -//resource "azurerm_resource_group" "test" { -// name = "acceptanceTestResourceGroup1" -// location = "West US" -//} -// -//resource "azurerm_network_security_group" "test" { -// name = "acceptanceTestSecurityGroup1" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -//} -// -//resource "azurerm_network_security_rule" "test" { -// name = "test123" -// priority = 100 -// direction = "Outbound" -// access = "Allow" -// protocol = "Tcp" -// source_port_range = "*" -// destination_port_range = "*" -// source_address_prefix = "*" -// destination_address_prefix = "*" -// resource_group_name = "${azurerm_resource_group.test.name}" -// network_security_group_name = "${azurerm_network_security_group.test.name}" -//} -//` -// -//var testAccAzureRMNetworkSecurityRule_updateBasic = ` -//resource "azurerm_resource_group" "test1" { -// name = "acceptanceTestResourceGroup2" -// location = "West US" -//} -// -//resource "azurerm_network_security_group" "test1" { -// name = "acceptanceTestSecurityGroup2" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test1.name}" -//} -// -//resource "azurerm_network_security_rule" "test1" { -// name = "test123" -// priority = 100 -// direction = "Outbound" -// access = "Allow" -// protocol = "Tcp" -// source_port_range = "*" -// destination_port_range = "*" -// source_address_prefix = "*" -// destination_address_prefix = "*" -// resource_group_name = "${azurerm_resource_group.test1.name}" -// network_security_group_name = "${azurerm_network_security_group.test1.name}" -//} -//` -// -//var testAccAzureRMNetworkSecurityRule_updateExtraRule = ` -//resource "azurerm_resource_group" "test1" { -// name = "acceptanceTestResourceGroup2" -// location = "West US" -//} -// -//resource "azurerm_network_security_group" "test1" { -// name = "acceptanceTestSecurityGroup2" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test1.name}" -//} -// -//resource "azurerm_network_security_rule" "test1" { -// name = "test123" -// priority = 100 -// direction = "Outbound" -// access = "Allow" -// protocol = "Tcp" -// source_port_range = "*" -// destination_port_range = "*" -// source_address_prefix = "*" -// destination_address_prefix = "*" -// resource_group_name = "${azurerm_resource_group.test1.name}" -// network_security_group_name = "${azurerm_network_security_group.test1.name}" -//} -// -//resource "azurerm_network_security_rule" "test2" { -// name = "testing456" -// priority = 101 -// direction = "Inbound" -// access = "Deny" -// protocol = "Tcp" -// source_port_range = "*" -// destination_port_range = "*" -// source_address_prefix = "*" -// destination_address_prefix = "*" -// resource_group_name = "${azurerm_resource_group.test1.name}" -// network_security_group_name = "${azurerm_network_security_group.test1.name}" -//} -//` +import ( + "fmt" + "net/http" + "testing" + + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAzureRMNetworkSecurityRule_basic(t *testing.T) { + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMNetworkSecurityRuleDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMNetworkSecurityRule_basic, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMNetworkSecurityRuleExists("azurerm_network_security_rule.test"), + ), + }, + }, + }) +} + +func TestAccAzureRMNetworkSecurityRule_addingRules(t *testing.T) { + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMNetworkSecurityRuleDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAzureRMNetworkSecurityRule_updateBasic, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMNetworkSecurityRuleExists("azurerm_network_security_rule.test1"), + ), + }, + + { + Config: testAccAzureRMNetworkSecurityRule_updateExtraRule, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMNetworkSecurityRuleExists("azurerm_network_security_rule.test2"), + ), + }, + }, + }) +} + +func testCheckAzureRMNetworkSecurityRuleExists(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + sgName := rs.Primary.Attributes["network_security_group_name"] + sgrName := rs.Primary.Attributes["name"] + resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] + if !hasResourceGroup { + return fmt.Errorf("Bad: no resource group found in state for network security rule: %s", sgName) + } + + conn := testAccProvider.Meta().(*ArmClient).secRuleClient + + resp, err := conn.Get(resourceGroup, sgName, sgrName) + if err != nil { + return fmt.Errorf("Bad: Get on secRuleClient: %s", err) + } + + if resp.StatusCode == http.StatusNotFound { + return fmt.Errorf("Bad: Network Security Rule %q (resource group: %q) (network security group: %q) does not exist", sgrName, sgName, resourceGroup) + } + + return nil + } +} + +func testCheckAzureRMNetworkSecurityRuleDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*ArmClient).secRuleClient + + for _, rs := range s.RootModule().Resources { + + if rs.Type != "azurerm_network_security_rule" { + continue + } + + sgName := rs.Primary.Attributes["network_security_group_name"] + sgrName := rs.Primary.Attributes["name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] + + resp, err := conn.Get(resourceGroup, sgName, sgrName) + + if err != nil { + return nil + } + + if resp.StatusCode != http.StatusNotFound { + return fmt.Errorf("Network Security Rule still exists:\n%#v", resp.Properties) + } + } + + return nil +} + +var testAccAzureRMNetworkSecurityRule_basic = ` +resource "azurerm_resource_group" "test" { + name = "acceptanceTestResourceGroup1" + location = "West US" +} + +resource "azurerm_network_security_group" "test" { + name = "acceptanceTestSecurityGroup1" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" +} + +resource "azurerm_network_security_rule" "test" { + name = "test123" + priority = 100 + direction = "Outbound" + access = "Allow" + protocol = "Tcp" + source_port_range = "*" + destination_port_range = "*" + source_address_prefix = "*" + destination_address_prefix = "*" + resource_group_name = "${azurerm_resource_group.test.name}" + network_security_group_name = "${azurerm_network_security_group.test.name}" +} +` + +var testAccAzureRMNetworkSecurityRule_updateBasic = ` +resource "azurerm_resource_group" "test1" { + name = "acceptanceTestResourceGroup2" + location = "West US" +} + +resource "azurerm_network_security_group" "test1" { + name = "acceptanceTestSecurityGroup2" + location = "West US" + resource_group_name = "${azurerm_resource_group.test1.name}" +} + +resource "azurerm_network_security_rule" "test1" { + name = "test123" + priority = 100 + direction = "Outbound" + access = "Allow" + protocol = "Tcp" + source_port_range = "*" + destination_port_range = "*" + source_address_prefix = "*" + destination_address_prefix = "*" + resource_group_name = "${azurerm_resource_group.test1.name}" + network_security_group_name = "${azurerm_network_security_group.test1.name}" +} +` + +var testAccAzureRMNetworkSecurityRule_updateExtraRule = ` +resource "azurerm_resource_group" "test1" { + name = "acceptanceTestResourceGroup2" + location = "West US" +} + +resource "azurerm_network_security_group" "test1" { + name = "acceptanceTestSecurityGroup2" + location = "West US" + resource_group_name = "${azurerm_resource_group.test1.name}" +} + +resource "azurerm_network_security_rule" "test1" { + name = "test123" + priority = 100 + direction = "Outbound" + access = "Allow" + protocol = "Tcp" + source_port_range = "*" + destination_port_range = "*" + source_address_prefix = "*" + destination_address_prefix = "*" + resource_group_name = "${azurerm_resource_group.test1.name}" + network_security_group_name = "${azurerm_network_security_group.test1.name}" +} + +resource "azurerm_network_security_rule" "test2" { + name = "testing456" + priority = 101 + direction = "Inbound" + access = "Deny" + protocol = "Tcp" + source_port_range = "*" + destination_port_range = "*" + source_address_prefix = "*" + destination_address_prefix = "*" + resource_group_name = "${azurerm_resource_group.test1.name}" + network_security_group_name = "${azurerm_network_security_group.test1.name}" +} +` From 0691c0eb91e1dcfa4f6b9bbdb7756ec370d9f940 Mon Sep 17 00:00:00 2001 From: James Nugent Date: Wed, 1 Jun 2016 19:32:25 -0500 Subject: [PATCH 14/17] provider/azurerm: Fix azurerm_template_deployment Tests are too slow to run. --- builtin/providers/azurerm/provider.go | 2 +- .../resource_arm_template_deployment.go | 431 +++++++-------- .../resource_arm_template_deployment_test.go | 498 +++++++++--------- 3 files changed, 470 insertions(+), 461 deletions(-) diff --git a/builtin/providers/azurerm/provider.go b/builtin/providers/azurerm/provider.go index 57ea897d4365..3f15d07ab5cc 100644 --- a/builtin/providers/azurerm/provider.go +++ b/builtin/providers/azurerm/provider.go @@ -60,7 +60,7 @@ func Provider() terraform.ResourceProvider { "azurerm_storage_container": resourceArmStorageContainer(), "azurerm_storage_queue": resourceArmStorageQueue(), "azurerm_subnet": resourceArmSubnet(), - //"azurerm_template_deployment": resourceArmTemplateDeployment(), + "azurerm_template_deployment": resourceArmTemplateDeployment(), //"azurerm_virtual_machine": resourceArmVirtualMachine(), "azurerm_virtual_network": resourceArmVirtualNetwork(), diff --git a/builtin/providers/azurerm/resource_arm_template_deployment.go b/builtin/providers/azurerm/resource_arm_template_deployment.go index d7dabf34ba6a..79f400715d85 100644 --- a/builtin/providers/azurerm/resource_arm_template_deployment.go +++ b/builtin/providers/azurerm/resource_arm_template_deployment.go @@ -1,213 +1,222 @@ package azurerm -//import ( -// "encoding/json" -// "fmt" -// "log" -// "net/http" -// "strings" -// "time" -// -// "github.com/Azure/azure-sdk-for-go/arm/resources/resources" -// "github.com/hashicorp/terraform/helper/resource" -// "github.com/hashicorp/terraform/helper/schema" -//) -// -//func resourceArmTemplateDeployment() *schema.Resource { -// return &schema.Resource{ -// Create: resourceArmTemplateDeploymentCreate, -// Read: resourceArmTemplateDeploymentRead, -// Update: resourceArmTemplateDeploymentCreate, -// Delete: resourceArmTemplateDeploymentDelete, -// -// Schema: map[string]*schema.Schema{ -// "name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// }, -// -// "resource_group_name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// }, -// -// "template_body": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// Computed: true, -// StateFunc: normalizeJson, -// }, -// -// "parameters": &schema.Schema{ -// Type: schema.TypeMap, -// Optional: true, -// }, -// -// "outputs": &schema.Schema{ -// Type: schema.TypeMap, -// Computed: true, -// }, -// -// "deployment_mode": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// }, -// } -//} -// -//func resourceArmTemplateDeploymentCreate(d *schema.ResourceData, meta interface{}) error { -// client := meta.(*ArmClient) -// deployClient := client.deploymentsClient -// -// name := d.Get("name").(string) -// resGroup := d.Get("resource_group_name").(string) -// deploymentMode := d.Get("deployment_mode").(string) -// -// log.Printf("[INFO] preparing arguments for Azure ARM Template Deployment creation.") -// properties := resources.DeploymentProperties{ -// Mode: resources.DeploymentMode(deploymentMode), -// } -// -// if v, ok := d.GetOk("parameters"); ok { -// params := v.(map[string]interface{}) -// -// newParams := make(map[string]interface{}, len(params)) -// for key, val := range params { -// newParams[key] = struct { -// Value interface{} -// }{ -// Value: val, -// } -// } -// -// properties.Parameters = &newParams -// } -// -// if v, ok := d.GetOk("template_body"); ok { -// template, err := expandTemplateBody(v.(string)) -// if err != nil { -// return err -// } -// -// properties.Template = &template -// } -// -// deployment := resources.Deployment{ -// Properties: &properties, -// } -// resp, err := deployClient.CreateOrUpdate(resGroup, name, deployment) -// if err != nil { -// return nil -// } -// -// d.SetId(*resp.ID) -// -// log.Printf("[DEBUG] Waiting for Template Deployment (%s) to become available", name) -// stateConf := &resource.StateChangeConf{ -// Pending: []string{"creating", "updating", "accepted", "running"}, -// Target: []string{"succeeded"}, -// Refresh: templateDeploymentStateRefreshFunc(client, resGroup, name), -// Timeout: 40 * time.Minute, -// } -// if _, err := stateConf.WaitForState(); err != nil { -// return fmt.Errorf("Error waiting for Template Deployment (%s) to become available: %s", name, err) -// } -// -// return resourceArmTemplateDeploymentRead(d, meta) -//} -// -//func resourceArmTemplateDeploymentRead(d *schema.ResourceData, meta interface{}) error { -// client := meta.(*ArmClient) -// deployClient := client.deploymentsClient -// -// id, err := parseAzureResourceID(d.Id()) -// if err != nil { -// return err -// } -// resGroup := id.ResourceGroup -// name := id.Path["deployments"] -// if name == "" { -// name = id.Path["Deployments"] -// } -// -// resp, err := deployClient.Get(resGroup, name) -// if resp.StatusCode == http.StatusNotFound { -// d.SetId("") -// return nil -// } -// if err != nil { -// return fmt.Errorf("Error making Read request on Azure RM Template Deployment %s: %s", name, err) -// } -// var outputs map[string]string -// if resp.Properties.Outputs != nil && len(*resp.Properties.Outputs) > 0 { -// outputs = make(map[string]string) -// for key, output := range *resp.Properties.Outputs { -// outputMap := output.(map[string]interface{}) -// outputValue, ok := outputMap["value"] -// if !ok { -// // No value -// continue -// } -// -// outputs[key] = outputValue.(string) -// } -// } -// -// d.Set("outputs", outputs) -// -// return nil -//} -// -//func resourceArmTemplateDeploymentDelete(d *schema.ResourceData, meta interface{}) error { -// client := meta.(*ArmClient) -// deployClient := client.deploymentsClient -// -// id, err := parseAzureResourceID(d.Id()) -// if err != nil { -// return err -// } -// resGroup := id.ResourceGroup -// name := id.Path["deployments"] -// if name == "" { -// name = id.Path["Deployments"] -// } -// -// _, err = deployClient.Delete(resGroup, name) -// return nil -//} -// -//func expandTemplateBody(template string) (map[string]interface{}, error) { -// var templateBody map[string]interface{} -// err := json.Unmarshal([]byte(template), &templateBody) -// if err != nil { -// return nil, fmt.Errorf("Error Expanding the template_body for Azure RM Template Deployment") -// } -// return templateBody, nil -//} -// -//func normalizeJson(jsonString interface{}) string { -// if jsonString == nil || jsonString == "" { -// return "" -// } -// var j interface{} -// err := json.Unmarshal([]byte(jsonString.(string)), &j) -// if err != nil { -// return fmt.Sprintf("Error parsing JSON: %s", err) -// } -// b, _ := json.Marshal(j) -// return string(b[:]) -//} -// -//func templateDeploymentStateRefreshFunc(client *ArmClient, resourceGroupName string, name string) resource.StateRefreshFunc { -// return func() (interface{}, string, error) { -// res, err := client.deploymentsClient.Get(resourceGroupName, name) -// if err != nil { -// return nil, "", fmt.Errorf("Error issuing read request in templateDeploymentStateRefreshFunc to Azure ARM for Template Deployment '%s' (RG: '%s'): %s", name, resourceGroupName, err) -// } -// -// return res, strings.ToLower(*res.Properties.ProvisioningState), nil -// } -//} +import ( + "encoding/json" + "fmt" + "log" + "net/http" + "strings" + "time" + + "github.com/Azure/azure-sdk-for-go/arm/resources/resources" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceArmTemplateDeployment() *schema.Resource { + return &schema.Resource{ + Create: resourceArmTemplateDeploymentCreate, + Read: resourceArmTemplateDeploymentRead, + Update: resourceArmTemplateDeploymentCreate, + Delete: resourceArmTemplateDeploymentDelete, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "resource_group_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "template_body": { + Type: schema.TypeString, + Optional: true, + Computed: true, + StateFunc: normalizeJson, + }, + + "parameters": { + Type: schema.TypeMap, + Optional: true, + }, + + "outputs": { + Type: schema.TypeMap, + Computed: true, + }, + + "deployment_mode": { + Type: schema.TypeString, + Required: true, + }, + }, + } +} + +func resourceArmTemplateDeploymentCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient) + deployClient := client.deploymentsClient + + name := d.Get("name").(string) + resGroup := d.Get("resource_group_name").(string) + deploymentMode := d.Get("deployment_mode").(string) + + log.Printf("[INFO] preparing arguments for Azure ARM Template Deployment creation.") + properties := resources.DeploymentProperties{ + Mode: resources.DeploymentMode(deploymentMode), + } + + if v, ok := d.GetOk("parameters"); ok { + params := v.(map[string]interface{}) + + newParams := make(map[string]interface{}, len(params)) + for key, val := range params { + newParams[key] = struct { + Value interface{} + }{ + Value: val, + } + } + + properties.Parameters = &newParams + } + + if v, ok := d.GetOk("template_body"); ok { + template, err := expandTemplateBody(v.(string)) + if err != nil { + return err + } + + properties.Template = &template + } + + deployment := resources.Deployment{ + Properties: &properties, + } + + _, err := deployClient.CreateOrUpdate(resGroup, name, deployment, make(chan struct{})) + if err != nil { + return nil + } + + read, err := deployClient.Get(resGroup, name) + if err != nil { + return err + } + if read.ID == nil { + return fmt.Errorf("Cannot read Template Deployment %s (resource group %s) ID", name, resGroup) + } + + d.SetId(*read.ID) + + log.Printf("[DEBUG] Waiting for Template Deployment (%s) to become available", name) + stateConf := &resource.StateChangeConf{ + Pending: []string{"creating", "updating", "accepted", "running"}, + Target: []string{"succeeded"}, + Refresh: templateDeploymentStateRefreshFunc(client, resGroup, name), + Timeout: 40 * time.Minute, + } + if _, err := stateConf.WaitForState(); err != nil { + return fmt.Errorf("Error waiting for Template Deployment (%s) to become available: %s", name, err) + } + + return resourceArmTemplateDeploymentRead(d, meta) +} + +func resourceArmTemplateDeploymentRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient) + deployClient := client.deploymentsClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + name := id.Path["deployments"] + if name == "" { + name = id.Path["Deployments"] + } + + resp, err := deployClient.Get(resGroup, name) + if resp.StatusCode == http.StatusNotFound { + d.SetId("") + return nil + } + if err != nil { + return fmt.Errorf("Error making Read request on Azure RM Template Deployment %s: %s", name, err) + } + var outputs map[string]string + if resp.Properties.Outputs != nil && len(*resp.Properties.Outputs) > 0 { + outputs = make(map[string]string) + for key, output := range *resp.Properties.Outputs { + outputMap := output.(map[string]interface{}) + outputValue, ok := outputMap["value"] + if !ok { + // No value + continue + } + + outputs[key] = outputValue.(string) + } + } + + d.Set("outputs", outputs) + + return nil +} + +func resourceArmTemplateDeploymentDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient) + deployClient := client.deploymentsClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + name := id.Path["deployments"] + if name == "" { + name = id.Path["Deployments"] + } + + _, err = deployClient.Delete(resGroup, name, make(chan struct{})) + return nil +} + +func expandTemplateBody(template string) (map[string]interface{}, error) { + var templateBody map[string]interface{} + err := json.Unmarshal([]byte(template), &templateBody) + if err != nil { + return nil, fmt.Errorf("Error Expanding the template_body for Azure RM Template Deployment") + } + return templateBody, nil +} + +func normalizeJson(jsonString interface{}) string { + if jsonString == nil || jsonString == "" { + return "" + } + var j interface{} + err := json.Unmarshal([]byte(jsonString.(string)), &j) + if err != nil { + return fmt.Sprintf("Error parsing JSON: %s", err) + } + b, _ := json.Marshal(j) + return string(b[:]) +} + +func templateDeploymentStateRefreshFunc(client *ArmClient, resourceGroupName string, name string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + res, err := client.deploymentsClient.Get(resourceGroupName, name) + if err != nil { + return nil, "", fmt.Errorf("Error issuing read request in templateDeploymentStateRefreshFunc to Azure ARM for Template Deployment '%s' (RG: '%s'): %s", name, resourceGroupName, err) + } + + return res, strings.ToLower(*res.Properties.ProvisioningState), nil + } +} diff --git a/builtin/providers/azurerm/resource_arm_template_deployment_test.go b/builtin/providers/azurerm/resource_arm_template_deployment_test.go index 0a3707d6454b..be23e9d60d98 100644 --- a/builtin/providers/azurerm/resource_arm_template_deployment_test.go +++ b/builtin/providers/azurerm/resource_arm_template_deployment_test.go @@ -1,251 +1,251 @@ 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 TestAccAzureRMTemplateDeployment_basic(t *testing.T) { -// ri := acctest.RandInt() -// config := fmt.Sprintf(testAccAzureRMTemplateDeployment_basicExample, ri, ri) -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// Providers: testAccProviders, -// CheckDestroy: testCheckAzureRMTemplateDeploymentDestroy, -// Steps: []resource.TestStep{ -// resource.TestStep{ -// Config: config, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMTemplateDeploymentExists("azurerm_template_deployment.test"), -// ), -// }, -// }, -// }) -//} -// -//func TestAccAzureRMTemplateDeployment_withParams(t *testing.T) { -// ri := acctest.RandInt() -// config := fmt.Sprintf(testAccAzureRMTemplateDeployment_withParams, ri, ri, ri) -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// Providers: testAccProviders, -// CheckDestroy: testCheckAzureRMTemplateDeploymentDestroy, -// Steps: []resource.TestStep{ -// resource.TestStep{ -// Config: config, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMTemplateDeploymentExists("azurerm_template_deployment.test"), -// resource.TestCheckResourceAttr("azurerm_template_deployment.test", "outputs.testOutput", "Output Value"), -// ), -// }, -// }, -// }) -//} -// -//func testCheckAzureRMTemplateDeploymentExists(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) -// } -// -// name := rs.Primary.Attributes["name"] -// resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] -// if !hasResourceGroup { -// return fmt.Errorf("Bad: no resource group found in state for template deployment: %s", name) -// } -// -// conn := testAccProvider.Meta().(*ArmClient).deploymentsClient -// -// resp, err := conn.Get(resourceGroup, name) -// if err != nil { -// return fmt.Errorf("Bad: Get on deploymentsClient: %s", err) -// } -// -// if resp.StatusCode == http.StatusNotFound { -// return fmt.Errorf("Bad: TemplateDeployment %q (resource group: %q) does not exist", name, resourceGroup) -// } -// -// return nil -// } -//} -// -//func testCheckAzureRMTemplateDeploymentDestroy(s *terraform.State) error { -// conn := testAccProvider.Meta().(*ArmClient).vmClient -// -// for _, rs := range s.RootModule().Resources { -// if rs.Type != "azurerm_template_deployment" { -// continue -// } -// -// name := rs.Primary.Attributes["name"] -// resourceGroup := rs.Primary.Attributes["resource_group_name"] -// -// resp, err := conn.Get(resourceGroup, name, "") -// -// if err != nil { -// return nil -// } -// -// if resp.StatusCode != http.StatusNotFound { -// return fmt.Errorf("Template Deployment still exists:\n%#v", resp.Properties) -// } -// } -// -// return nil -//} -// -//var testAccAzureRMTemplateDeployment_basicExample = ` -// resource "azurerm_resource_group" "test" { -// name = "acctestrg-%d" -// location = "West US" -// } -// -// resource "azurerm_template_deployment" "test" { -// name = "acctesttemplate-%d" -// resource_group_name = "${azurerm_resource_group.test.name}" -// template_body = < Date: Wed, 1 Jun 2016 19:44:08 -0500 Subject: [PATCH 15/17] provider/azurerm: Fix CDN resources --- builtin/providers/azurerm/provider.go | 6 +- .../azurerm/resource_arm_cdn_endpoint.go | 881 +++++++++--------- .../azurerm/resource_arm_cdn_endpoint_test.go | 424 +++++---- .../azurerm/resource_arm_cdn_profile.go | 353 ++++--- .../azurerm/resource_arm_cdn_profile_test.go | 410 ++++---- 5 files changed, 1020 insertions(+), 1054 deletions(-) diff --git a/builtin/providers/azurerm/provider.go b/builtin/providers/azurerm/provider.go index 3f15d07ab5cc..395359b439f2 100644 --- a/builtin/providers/azurerm/provider.go +++ b/builtin/providers/azurerm/provider.go @@ -45,9 +45,9 @@ func Provider() terraform.ResourceProvider { ResourcesMap: map[string]*schema.Resource{ // These resources use the Azure ARM SDK - "azurerm_availability_set": resourceArmAvailabilitySet(), - //"azurerm_cdn_endpoint": resourceArmCdnEndpoint(), - //"azurerm_cdn_profile": resourceArmCdnProfile(), + "azurerm_availability_set": resourceArmAvailabilitySet(), + "azurerm_cdn_endpoint": resourceArmCdnEndpoint(), + "azurerm_cdn_profile": resourceArmCdnProfile(), "azurerm_local_network_gateway": resourceArmLocalNetworkGateway(), "azurerm_network_interface": resourceArmNetworkInterface(), "azurerm_network_security_group": resourceArmNetworkSecurityGroup(), diff --git a/builtin/providers/azurerm/resource_arm_cdn_endpoint.go b/builtin/providers/azurerm/resource_arm_cdn_endpoint.go index 01c290fa9e03..b0afc691a587 100644 --- a/builtin/providers/azurerm/resource_arm_cdn_endpoint.go +++ b/builtin/providers/azurerm/resource_arm_cdn_endpoint.go @@ -1,451 +1,434 @@ package azurerm -//import ( -// "bytes" -// "fmt" -// "log" -// "net/http" -// "strings" -// "time" -// -// "github.com/Azure/azure-sdk-for-go/arm/cdn" -// "github.com/hashicorp/terraform/helper/hashcode" -// "github.com/hashicorp/terraform/helper/resource" -// "github.com/hashicorp/terraform/helper/schema" -//) -// -//func resourceArmCdnEndpoint() *schema.Resource { -// return &schema.Resource{ -// Create: resourceArmCdnEndpointCreate, -// Read: resourceArmCdnEndpointRead, -// Update: resourceArmCdnEndpointUpdate, -// Delete: resourceArmCdnEndpointDelete, -// -// Schema: map[string]*schema.Schema{ -// "name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// }, -// -// "location": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// StateFunc: azureRMNormalizeLocation, -// }, -// -// "resource_group_name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// }, -// -// "profile_name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// }, -// -// "origin_host_header": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// Computed: true, -// }, -// -// "is_http_allowed": &schema.Schema{ -// Type: schema.TypeBool, -// Optional: true, -// Default: true, -// }, -// -// "is_https_allowed": &schema.Schema{ -// Type: schema.TypeBool, -// Optional: true, -// Default: true, -// }, -// -// "origin": &schema.Schema{ -// Type: schema.TypeSet, -// Required: true, -// Elem: &schema.Resource{ -// Schema: map[string]*schema.Schema{ -// "name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "host_name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "http_port": &schema.Schema{ -// Type: schema.TypeInt, -// Optional: true, -// Computed: true, -// }, -// -// "https_port": &schema.Schema{ -// Type: schema.TypeInt, -// Optional: true, -// Computed: true, -// }, -// }, -// }, -// Set: resourceArmCdnEndpointOriginHash, -// }, -// -// "origin_path": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// Computed: true, -// }, -// -// "querystring_caching_behaviour": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// Default: "IgnoreQueryString", -// ValidateFunc: validateCdnEndpointQuerystringCachingBehaviour, -// }, -// -// "content_types_to_compress": &schema.Schema{ -// Type: schema.TypeSet, -// Optional: true, -// Computed: true, -// Elem: &schema.Schema{Type: schema.TypeString}, -// Set: schema.HashString, -// }, -// -// "is_compression_enabled": &schema.Schema{ -// Type: schema.TypeBool, -// Optional: true, -// Default: false, -// }, -// -// "host_name": &schema.Schema{ -// Type: schema.TypeString, -// Computed: true, -// }, -// -// "tags": tagsSchema(), -// }, -// } -//} -// -//func resourceArmCdnEndpointCreate(d *schema.ResourceData, meta interface{}) error { -// client := meta.(*ArmClient) -// cdnEndpointsClient := client.cdnEndpointsClient -// -// log.Printf("[INFO] preparing arguments for Azure ARM CDN EndPoint creation.") -// -// name := d.Get("name").(string) -// location := d.Get("location").(string) -// resGroup := d.Get("resource_group_name").(string) -// profileName := d.Get("profile_name").(string) -// http_allowed := d.Get("is_http_allowed").(bool) -// https_allowed := d.Get("is_https_allowed").(bool) -// compression_enabled := d.Get("is_compression_enabled").(bool) -// caching_behaviour := d.Get("querystring_caching_behaviour").(string) -// tags := d.Get("tags").(map[string]interface{}) -// -// properties := cdn.EndpointPropertiesCreateUpdateParameters{ -// IsHTTPAllowed: &http_allowed, -// IsHTTPSAllowed: &https_allowed, -// IsCompressionEnabled: &compression_enabled, -// QueryStringCachingBehavior: cdn.QueryStringCachingBehavior(caching_behaviour), -// } -// -// origins, originsErr := expandAzureRmCdnEndpointOrigins(d) -// if originsErr != nil { -// return fmt.Errorf("Error Building list of CDN Endpoint Origins: %s", originsErr) -// } -// if len(origins) > 0 { -// properties.Origins = &origins -// } -// -// if v, ok := d.GetOk("origin_host_header"); ok { -// host_header := v.(string) -// properties.OriginHostHeader = &host_header -// } -// -// if v, ok := d.GetOk("origin_path"); ok { -// origin_path := v.(string) -// properties.OriginPath = &origin_path -// } -// -// if v, ok := d.GetOk("content_types_to_compress"); ok { -// var content_types []string -// ctypes := v.(*schema.Set).List() -// for _, ct := range ctypes { -// str := ct.(string) -// content_types = append(content_types, str) -// } -// -// properties.ContentTypesToCompress = &content_types -// } -// -// cdnEndpoint := cdn.EndpointCreateParameters{ -// Location: &location, -// Properties: &properties, -// Tags: expandTags(tags), -// } -// -// resp, err := cdnEndpointsClient.Create(name, cdnEndpoint, profileName, resGroup) -// if err != nil { -// return err -// } -// -// d.SetId(*resp.ID) -// -// log.Printf("[DEBUG] Waiting for CDN Endpoint (%s) to become available", name) -// stateConf := &resource.StateChangeConf{ -// Pending: []string{"Accepted", "Updating", "Creating"}, -// Target: []string{"Succeeded"}, -// Refresh: cdnEndpointStateRefreshFunc(client, resGroup, profileName, name), -// Timeout: 10 * time.Minute, -// } -// if _, err := stateConf.WaitForState(); err != nil { -// return fmt.Errorf("Error waiting for CDN Endpoint (%s) to become available: %s", name, err) -// } -// -// return resourceArmCdnEndpointRead(d, meta) -//} -// -//func resourceArmCdnEndpointRead(d *schema.ResourceData, meta interface{}) error { -// cdnEndpointsClient := meta.(*ArmClient).cdnEndpointsClient -// -// id, err := parseAzureResourceID(d.Id()) -// if err != nil { -// return err -// } -// resGroup := id.ResourceGroup -// name := id.Path["endpoints"] -// profileName := id.Path["profiles"] -// if profileName == "" { -// profileName = id.Path["Profiles"] -// } -// log.Printf("[INFO] Trying to find the AzureRM CDN Endpoint %s (Profile: %s, RG: %s)", name, profileName, resGroup) -// resp, err := cdnEndpointsClient.Get(name, profileName, resGroup) -// if resp.StatusCode == http.StatusNotFound { -// d.SetId("") -// return nil -// } -// if err != nil { -// return fmt.Errorf("Error making Read request on Azure CDN Endpoint %s: %s", name, err) -// } -// -// d.Set("name", resp.Name) -// d.Set("host_name", resp.Properties.HostName) -// d.Set("is_compression_enabled", resp.Properties.IsCompressionEnabled) -// d.Set("is_http_allowed", resp.Properties.IsHTTPAllowed) -// d.Set("is_https_allowed", resp.Properties.IsHTTPSAllowed) -// d.Set("querystring_caching_behaviour", resp.Properties.QueryStringCachingBehavior) -// if resp.Properties.OriginHostHeader != nil && *resp.Properties.OriginHostHeader != "" { -// d.Set("origin_host_header", resp.Properties.OriginHostHeader) -// } -// if resp.Properties.OriginPath != nil && *resp.Properties.OriginPath != "" { -// d.Set("origin_path", resp.Properties.OriginPath) -// } -// if resp.Properties.ContentTypesToCompress != nil && len(*resp.Properties.ContentTypesToCompress) > 0 { -// d.Set("content_types_to_compress", flattenAzureRMCdnEndpointContentTypes(resp.Properties.ContentTypesToCompress)) -// } -// d.Set("origin", flattenAzureRMCdnEndpointOrigin(resp.Properties.Origins)) -// -// flattenAndSetTags(d, resp.Tags) -// -// return nil -//} -// -//func resourceArmCdnEndpointUpdate(d *schema.ResourceData, meta interface{}) error { -// cdnEndpointsClient := meta.(*ArmClient).cdnEndpointsClient -// -// if !d.HasChange("tags") { -// return nil -// } -// -// name := d.Get("name").(string) -// resGroup := d.Get("resource_group_name").(string) -// profileName := d.Get("profile_name").(string) -// http_allowed := d.Get("is_http_allowed").(bool) -// https_allowed := d.Get("is_https_allowed").(bool) -// compression_enabled := d.Get("is_compression_enabled").(bool) -// caching_behaviour := d.Get("querystring_caching_behaviour").(string) -// newTags := d.Get("tags").(map[string]interface{}) -// -// properties := cdn.EndpointPropertiesCreateUpdateParameters{ -// IsHTTPAllowed: &http_allowed, -// IsHTTPSAllowed: &https_allowed, -// IsCompressionEnabled: &compression_enabled, -// QueryStringCachingBehavior: cdn.QueryStringCachingBehavior(caching_behaviour), -// } -// -// if d.HasChange("origin") { -// origins, originsErr := expandAzureRmCdnEndpointOrigins(d) -// if originsErr != nil { -// return fmt.Errorf("Error Building list of CDN Endpoint Origins: %s", originsErr) -// } -// if len(origins) > 0 { -// properties.Origins = &origins -// } -// } -// -// if d.HasChange("origin_host_header") { -// host_header := d.Get("origin_host_header").(string) -// properties.OriginHostHeader = &host_header -// } -// -// if d.HasChange("origin_path") { -// origin_path := d.Get("origin_path").(string) -// properties.OriginPath = &origin_path -// } -// -// if d.HasChange("content_types_to_compress") { -// var content_types []string -// ctypes := d.Get("content_types_to_compress").(*schema.Set).List() -// for _, ct := range ctypes { -// str := ct.(string) -// content_types = append(content_types, str) -// } -// -// properties.ContentTypesToCompress = &content_types -// } -// -// updateProps := cdn.EndpointUpdateParameters{ -// Tags: expandTags(newTags), -// Properties: &properties, -// } -// -// _, err := cdnEndpointsClient.Update(name, updateProps, profileName, resGroup) -// if err != nil { -// return fmt.Errorf("Error issuing Azure ARM update request to update CDN Endpoint %q: %s", name, err) -// } -// -// return resourceArmCdnEndpointRead(d, meta) -//} -// -//func resourceArmCdnEndpointDelete(d *schema.ResourceData, meta interface{}) error { -// client := meta.(*ArmClient).cdnEndpointsClient -// -// id, err := parseAzureResourceID(d.Id()) -// if err != nil { -// return err -// } -// resGroup := id.ResourceGroup -// profileName := id.Path["profiles"] -// if profileName == "" { -// profileName = id.Path["Profiles"] -// } -// name := id.Path["endpoints"] -// -// accResp, err := client.DeleteIfExists(name, profileName, resGroup) -// if err != nil { -// if accResp.StatusCode == http.StatusNotFound { -// return nil -// } -// return fmt.Errorf("Error issuing AzureRM delete request for CDN Endpoint %q: %s", name, err) -// } -// _, err = pollIndefinitelyAsNeeded(client.Client, accResp.Response, http.StatusNotFound) -// if err != nil { -// return fmt.Errorf("Error polling for AzureRM delete request for CDN Endpoint %q: %s", name, err) -// } -// -// return err -//} -// -//func cdnEndpointStateRefreshFunc(client *ArmClient, resourceGroupName string, profileName string, name string) resource.StateRefreshFunc { -// return func() (interface{}, string, error) { -// res, err := client.cdnEndpointsClient.Get(name, profileName, resourceGroupName) -// if err != nil { -// return nil, "", fmt.Errorf("Error issuing read request in cdnEndpointStateRefreshFunc to Azure ARM for CDN Endpoint '%s' (RG: '%s'): %s", name, resourceGroupName, err) -// } -// return res, string(res.Properties.ProvisioningState), nil -// } -//} -// -//func validateCdnEndpointQuerystringCachingBehaviour(v interface{}, k string) (ws []string, errors []error) { -// value := strings.ToLower(v.(string)) -// cachingTypes := map[string]bool{ -// "ignorequerystring": true, -// "bypasscaching": true, -// "usequerystring": true, -// } -// -// if !cachingTypes[value] { -// errors = append(errors, fmt.Errorf("CDN Endpoint querystringCachingBehaviours can only be IgnoreQueryString, BypassCaching or UseQueryString")) -// } -// return -//} -// -//func resourceArmCdnEndpointOriginHash(v interface{}) int { -// var buf bytes.Buffer -// m := v.(map[string]interface{}) -// buf.WriteString(fmt.Sprintf("%s-", m["name"].(string))) -// buf.WriteString(fmt.Sprintf("%s-", m["host_name"].(string))) -// -// return hashcode.String(buf.String()) -//} -// -//func expandAzureRmCdnEndpointOrigins(d *schema.ResourceData) ([]cdn.DeepCreatedOrigin, error) { -// configs := d.Get("origin").(*schema.Set).List() -// origins := make([]cdn.DeepCreatedOrigin, 0, len(configs)) -// -// for _, configRaw := range configs { -// data := configRaw.(map[string]interface{}) -// -// host_name := data["host_name"].(string) -// -// properties := cdn.DeepCreatedOriginProperties{ -// HostName: &host_name, -// } -// -// if v, ok := data["https_port"]; ok { -// https_port := v.(int) -// properties.HTTPSPort = &https_port -// -// } -// -// if v, ok := data["http_port"]; ok { -// http_port := v.(int) -// properties.HTTPPort = &http_port -// } -// -// name := data["name"].(string) -// -// origin := cdn.DeepCreatedOrigin{ -// Name: &name, -// Properties: &properties, -// } -// -// origins = append(origins, origin) -// } -// -// return origins, nil -//} -// -//func flattenAzureRMCdnEndpointOrigin(list *[]cdn.DeepCreatedOrigin) []map[string]interface{} { -// result := make([]map[string]interface{}, 0, len(*list)) -// for _, i := range *list { -// l := map[string]interface{}{ -// "name": *i.Name, -// "host_name": *i.Properties.HostName, -// } -// -// if i.Properties.HTTPPort != nil { -// l["http_port"] = *i.Properties.HTTPPort -// } -// if i.Properties.HTTPSPort != nil { -// l["https_port"] = *i.Properties.HTTPSPort -// } -// result = append(result, l) -// } -// return result -//} -// -//func flattenAzureRMCdnEndpointContentTypes(list *[]string) []interface{} { -// vs := make([]interface{}, 0, len(*list)) -// for _, v := range *list { -// vs = append(vs, v) -// } -// return vs -//} +import ( + "bytes" + "fmt" + "log" + "net/http" + "strings" + + "github.com/Azure/azure-sdk-for-go/arm/cdn" + "github.com/hashicorp/terraform/helper/hashcode" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceArmCdnEndpoint() *schema.Resource { + return &schema.Resource{ + Create: resourceArmCdnEndpointCreate, + Read: resourceArmCdnEndpointRead, + Update: resourceArmCdnEndpointUpdate, + Delete: resourceArmCdnEndpointDelete, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "location": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + StateFunc: azureRMNormalizeLocation, + }, + + "resource_group_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "profile_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "origin_host_header": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + + "is_http_allowed": { + Type: schema.TypeBool, + Optional: true, + Default: true, + }, + + "is_https_allowed": { + Type: schema.TypeBool, + Optional: true, + Default: true, + }, + + "origin": { + Type: schema.TypeSet, + Required: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + }, + + "host_name": { + Type: schema.TypeString, + Required: true, + }, + + "http_port": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + + "https_port": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + }, + }, + }, + Set: resourceArmCdnEndpointOriginHash, + }, + + "origin_path": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + + "querystring_caching_behaviour": { + Type: schema.TypeString, + Optional: true, + Default: "IgnoreQueryString", + ValidateFunc: validateCdnEndpointQuerystringCachingBehaviour, + }, + + "content_types_to_compress": { + Type: schema.TypeSet, + Optional: true, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Set: schema.HashString, + }, + + "is_compression_enabled": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + + "host_name": { + Type: schema.TypeString, + Computed: true, + }, + + "tags": tagsSchema(), + }, + } +} + +func resourceArmCdnEndpointCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient) + cdnEndpointsClient := client.cdnEndpointsClient + + log.Printf("[INFO] preparing arguments for Azure ARM CDN EndPoint creation.") + + name := d.Get("name").(string) + location := d.Get("location").(string) + resGroup := d.Get("resource_group_name").(string) + profileName := d.Get("profile_name").(string) + http_allowed := d.Get("is_http_allowed").(bool) + https_allowed := d.Get("is_https_allowed").(bool) + compression_enabled := d.Get("is_compression_enabled").(bool) + caching_behaviour := d.Get("querystring_caching_behaviour").(string) + tags := d.Get("tags").(map[string]interface{}) + + properties := cdn.EndpointPropertiesCreateUpdateParameters{ + IsHTTPAllowed: &http_allowed, + IsHTTPSAllowed: &https_allowed, + IsCompressionEnabled: &compression_enabled, + QueryStringCachingBehavior: cdn.QueryStringCachingBehavior(caching_behaviour), + } + + origins, originsErr := expandAzureRmCdnEndpointOrigins(d) + if originsErr != nil { + return fmt.Errorf("Error Building list of CDN Endpoint Origins: %s", originsErr) + } + if len(origins) > 0 { + properties.Origins = &origins + } + + if v, ok := d.GetOk("origin_host_header"); ok { + host_header := v.(string) + properties.OriginHostHeader = &host_header + } + + if v, ok := d.GetOk("origin_path"); ok { + origin_path := v.(string) + properties.OriginPath = &origin_path + } + + if v, ok := d.GetOk("content_types_to_compress"); ok { + var content_types []string + ctypes := v.(*schema.Set).List() + for _, ct := range ctypes { + str := ct.(string) + content_types = append(content_types, str) + } + + properties.ContentTypesToCompress = &content_types + } + + cdnEndpoint := cdn.EndpointCreateParameters{ + Location: &location, + Properties: &properties, + Tags: expandTags(tags), + } + + _, err := cdnEndpointsClient.Create(name, cdnEndpoint, profileName, resGroup, make(chan struct{})) + if err != nil { + return err + } + + read, err := cdnEndpointsClient.Get(name, profileName, resGroup) + if err != nil { + return err + } + if read.ID == nil { + return fmt.Errorf("Cannot read CND Endpoint %s/%s (resource group %s) ID", profileName, name, resGroup) + } + + d.SetId(*read.ID) + + return resourceArmCdnEndpointRead(d, meta) +} + +func resourceArmCdnEndpointRead(d *schema.ResourceData, meta interface{}) error { + cdnEndpointsClient := meta.(*ArmClient).cdnEndpointsClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + name := id.Path["endpoints"] + profileName := id.Path["profiles"] + if profileName == "" { + profileName = id.Path["Profiles"] + } + log.Printf("[INFO] Trying to find the AzureRM CDN Endpoint %s (Profile: %s, RG: %s)", name, profileName, resGroup) + resp, err := cdnEndpointsClient.Get(name, profileName, resGroup) + if resp.StatusCode == http.StatusNotFound { + d.SetId("") + return nil + } + if err != nil { + return fmt.Errorf("Error making Read request on Azure CDN Endpoint %s: %s", name, err) + } + + d.Set("name", resp.Name) + d.Set("host_name", resp.Properties.HostName) + d.Set("is_compression_enabled", resp.Properties.IsCompressionEnabled) + d.Set("is_http_allowed", resp.Properties.IsHTTPAllowed) + d.Set("is_https_allowed", resp.Properties.IsHTTPSAllowed) + d.Set("querystring_caching_behaviour", resp.Properties.QueryStringCachingBehavior) + if resp.Properties.OriginHostHeader != nil && *resp.Properties.OriginHostHeader != "" { + d.Set("origin_host_header", resp.Properties.OriginHostHeader) + } + if resp.Properties.OriginPath != nil && *resp.Properties.OriginPath != "" { + d.Set("origin_path", resp.Properties.OriginPath) + } + if resp.Properties.ContentTypesToCompress != nil && len(*resp.Properties.ContentTypesToCompress) > 0 { + d.Set("content_types_to_compress", flattenAzureRMCdnEndpointContentTypes(resp.Properties.ContentTypesToCompress)) + } + d.Set("origin", flattenAzureRMCdnEndpointOrigin(resp.Properties.Origins)) + + flattenAndSetTags(d, resp.Tags) + + return nil +} + +func resourceArmCdnEndpointUpdate(d *schema.ResourceData, meta interface{}) error { + cdnEndpointsClient := meta.(*ArmClient).cdnEndpointsClient + + if !d.HasChange("tags") { + return nil + } + + name := d.Get("name").(string) + resGroup := d.Get("resource_group_name").(string) + profileName := d.Get("profile_name").(string) + http_allowed := d.Get("is_http_allowed").(bool) + https_allowed := d.Get("is_https_allowed").(bool) + compression_enabled := d.Get("is_compression_enabled").(bool) + caching_behaviour := d.Get("querystring_caching_behaviour").(string) + newTags := d.Get("tags").(map[string]interface{}) + + properties := cdn.EndpointPropertiesCreateUpdateParameters{ + IsHTTPAllowed: &http_allowed, + IsHTTPSAllowed: &https_allowed, + IsCompressionEnabled: &compression_enabled, + QueryStringCachingBehavior: cdn.QueryStringCachingBehavior(caching_behaviour), + } + + if d.HasChange("origin") { + origins, originsErr := expandAzureRmCdnEndpointOrigins(d) + if originsErr != nil { + return fmt.Errorf("Error Building list of CDN Endpoint Origins: %s", originsErr) + } + if len(origins) > 0 { + properties.Origins = &origins + } + } + + if d.HasChange("origin_host_header") { + host_header := d.Get("origin_host_header").(string) + properties.OriginHostHeader = &host_header + } + + if d.HasChange("origin_path") { + origin_path := d.Get("origin_path").(string) + properties.OriginPath = &origin_path + } + + if d.HasChange("content_types_to_compress") { + var content_types []string + ctypes := d.Get("content_types_to_compress").(*schema.Set).List() + for _, ct := range ctypes { + str := ct.(string) + content_types = append(content_types, str) + } + + properties.ContentTypesToCompress = &content_types + } + + updateProps := cdn.EndpointUpdateParameters{ + Tags: expandTags(newTags), + Properties: &properties, + } + + _, err := cdnEndpointsClient.Update(name, updateProps, profileName, resGroup) + if err != nil { + return fmt.Errorf("Error issuing Azure ARM update request to update CDN Endpoint %q: %s", name, err) + } + + return resourceArmCdnEndpointRead(d, meta) +} + +func resourceArmCdnEndpointDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).cdnEndpointsClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + profileName := id.Path["profiles"] + if profileName == "" { + profileName = id.Path["Profiles"] + } + name := id.Path["endpoints"] + + accResp, err := client.DeleteIfExists(name, profileName, resGroup, make(chan struct{})) + if err != nil { + if accResp.StatusCode == http.StatusNotFound { + return nil + } + return fmt.Errorf("Error issuing AzureRM delete request for CDN Endpoint %q: %s", name, err) + } + + return err +} + +func validateCdnEndpointQuerystringCachingBehaviour(v interface{}, k string) (ws []string, errors []error) { + value := strings.ToLower(v.(string)) + cachingTypes := map[string]bool{ + "ignorequerystring": true, + "bypasscaching": true, + "usequerystring": true, + } + + if !cachingTypes[value] { + errors = append(errors, fmt.Errorf("CDN Endpoint querystringCachingBehaviours can only be IgnoreQueryString, BypassCaching or UseQueryString")) + } + return +} + +func resourceArmCdnEndpointOriginHash(v interface{}) int { + var buf bytes.Buffer + m := v.(map[string]interface{}) + buf.WriteString(fmt.Sprintf("%s-", m["name"].(string))) + buf.WriteString(fmt.Sprintf("%s-", m["host_name"].(string))) + + return hashcode.String(buf.String()) +} + +func expandAzureRmCdnEndpointOrigins(d *schema.ResourceData) ([]cdn.DeepCreatedOrigin, error) { + configs := d.Get("origin").(*schema.Set).List() + origins := make([]cdn.DeepCreatedOrigin, 0, len(configs)) + + for _, configRaw := range configs { + data := configRaw.(map[string]interface{}) + + host_name := data["host_name"].(string) + + properties := cdn.DeepCreatedOriginProperties{ + HostName: &host_name, + } + + if v, ok := data["https_port"]; ok { + https_port := int32(v.(int)) + properties.HTTPSPort = &https_port + + } + + if v, ok := data["http_port"]; ok { + http_port := int32(v.(int)) + properties.HTTPPort = &http_port + } + + name := data["name"].(string) + + origin := cdn.DeepCreatedOrigin{ + Name: &name, + Properties: &properties, + } + + origins = append(origins, origin) + } + + return origins, nil +} + +func flattenAzureRMCdnEndpointOrigin(list *[]cdn.DeepCreatedOrigin) []map[string]interface{} { + result := make([]map[string]interface{}, 0, len(*list)) + for _, i := range *list { + l := map[string]interface{}{ + "name": *i.Name, + "host_name": *i.Properties.HostName, + } + + if i.Properties.HTTPPort != nil { + l["http_port"] = *i.Properties.HTTPPort + } + if i.Properties.HTTPSPort != nil { + l["https_port"] = *i.Properties.HTTPSPort + } + result = append(result, l) + } + return result +} + +func flattenAzureRMCdnEndpointContentTypes(list *[]string) []interface{} { + vs := make([]interface{}, 0, len(*list)) + for _, v := range *list { + vs = append(vs, v) + } + return vs +} diff --git a/builtin/providers/azurerm/resource_arm_cdn_endpoint_test.go b/builtin/providers/azurerm/resource_arm_cdn_endpoint_test.go index bd2a93fc5fbc..705564ebcb7a 100644 --- a/builtin/providers/azurerm/resource_arm_cdn_endpoint_test.go +++ b/builtin/providers/azurerm/resource_arm_cdn_endpoint_test.go @@ -1,215 +1,213 @@ 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 TestAccAzureRMCdnEndpoint_basic(t *testing.T) { -// -// ri := acctest.RandInt() -// config := fmt.Sprintf(testAccAzureRMCdnEndpoint_basic, ri, ri, ri) -// -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// Providers: testAccProviders, -// CheckDestroy: testCheckAzureRMCdnEndpointDestroy, -// Steps: []resource.TestStep{ -// resource.TestStep{ -// Config: config, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMCdnEndpointExists("azurerm_cdn_endpoint.test"), -// ), -// }, -// }, -// }) -//} -// -//func TestAccAzureRMCdnEndpoints_withTags(t *testing.T) { -// -// ri := acctest.RandInt() -// preConfig := fmt.Sprintf(testAccAzureRMCdnEndpoint_withTags, ri, ri, ri) -// postConfig := fmt.Sprintf(testAccAzureRMCdnEndpoint_withTagsUpdate, ri, ri, ri) -// -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// Providers: testAccProviders, -// CheckDestroy: testCheckAzureRMCdnEndpointDestroy, -// Steps: []resource.TestStep{ -// resource.TestStep{ -// Config: preConfig, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMCdnEndpointExists("azurerm_cdn_endpoint.test"), -// resource.TestCheckResourceAttr( -// "azurerm_cdn_endpoint.test", "tags.#", "2"), -// resource.TestCheckResourceAttr( -// "azurerm_cdn_endpoint.test", "tags.environment", "Production"), -// resource.TestCheckResourceAttr( -// "azurerm_cdn_endpoint.test", "tags.cost_center", "MSFT"), -// ), -// }, -// -// resource.TestStep{ -// Config: postConfig, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMCdnEndpointExists("azurerm_cdn_endpoint.test"), -// resource.TestCheckResourceAttr( -// "azurerm_cdn_endpoint.test", "tags.#", "1"), -// resource.TestCheckResourceAttr( -// "azurerm_cdn_endpoint.test", "tags.environment", "staging"), -// ), -// }, -// }, -// }) -//} -// -//func testCheckAzureRMCdnEndpointExists(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) -// } -// -// name := rs.Primary.Attributes["name"] -// profileName := rs.Primary.Attributes["profile_name"] -// resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] -// if !hasResourceGroup { -// return fmt.Errorf("Bad: no resource group found in state for cdn endpoint: %s", name) -// } -// -// conn := testAccProvider.Meta().(*ArmClient).cdnEndpointsClient -// -// resp, err := conn.Get(name, profileName, resourceGroup) -// if err != nil { -// return fmt.Errorf("Bad: Get on cdnEndpointsClient: %s", err) -// } -// -// if resp.StatusCode == http.StatusNotFound { -// return fmt.Errorf("Bad: CDN Endpoint %q (resource group: %q) does not exist", name, resourceGroup) -// } -// -// return nil -// } -//} -// -//func testCheckAzureRMCdnEndpointDestroy(s *terraform.State) error { -// conn := testAccProvider.Meta().(*ArmClient).cdnEndpointsClient -// -// for _, rs := range s.RootModule().Resources { -// if rs.Type != "azurerm_cdn_endpoint" { -// continue -// } -// -// name := rs.Primary.Attributes["name"] -// resourceGroup := rs.Primary.Attributes["resource_group_name"] -// profileName := rs.Primary.Attributes["profile_name"] -// -// resp, err := conn.Get(name, profileName, resourceGroup) -// -// if err != nil { -// return nil -// } -// -// if resp.StatusCode != http.StatusNotFound { -// return fmt.Errorf("CDN Endpoint still exists:\n%#v", resp.Properties) -// } -// } -// -// return nil -//} -// -//var testAccAzureRMCdnEndpoint_basic = ` -//resource "azurerm_resource_group" "test" { -// name = "acctestrg-%d" -// location = "West US" -//} -//resource "azurerm_cdn_profile" "test" { -// name = "acctestcdnprof%d" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// sku = "Standard" -//} -// -//resource "azurerm_cdn_endpoint" "test" { -// name = "acctestcdnend%d" -// profile_name = "${azurerm_cdn_profile.test.name}" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// -// origin { -// name = "acceptanceTestCdnOrigin1" -// host_name = "www.example.com" -// https_port = 443 -// http_port = 80 -// } -//} -//` -// -//var testAccAzureRMCdnEndpoint_withTags = ` -//resource "azurerm_resource_group" "test" { -// name = "acctestrg-%d" -// location = "West US" -//} -//resource "azurerm_cdn_profile" "test" { -// name = "acctestcdnprof%d" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// sku = "Standard" -//} -// -//resource "azurerm_cdn_endpoint" "test" { -// name = "acctestcdnend%d" -// profile_name = "${azurerm_cdn_profile.test.name}" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// -// origin { -// name = "acceptanceTestCdnOrigin2" -// host_name = "www.example.com" -// https_port = 443 -// http_port = 80 -// } -// -// tags { -// environment = "Production" -// cost_center = "MSFT" -// } -//} -//` -// -//var testAccAzureRMCdnEndpoint_withTagsUpdate = ` -//resource "azurerm_resource_group" "test" { -// name = "acctestrg-%d" -// location = "West US" -//} -//resource "azurerm_cdn_profile" "test" { -// name = "acctestcdnprof%d" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// sku = "Standard" -//} -// -//resource "azurerm_cdn_endpoint" "test" { -// name = "acctestcdnend%d" -// profile_name = "${azurerm_cdn_profile.test.name}" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// -// origin { -// name = "acceptanceTestCdnOrigin2" -// host_name = "www.example.com" -// https_port = 443 -// http_port = 80 -// } -// -// tags { -// environment = "staging" -// } -//} -//` +import ( + "fmt" + "net/http" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAzureRMCdnEndpoint_basic(t *testing.T) { + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMCdnEndpoint_basic, ri, ri, ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMCdnEndpointDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMCdnEndpointExists("azurerm_cdn_endpoint.test"), + ), + }, + }, + }) +} + +func TestAccAzureRMCdnEndpoint_withTags(t *testing.T) { + ri := acctest.RandInt() + preConfig := fmt.Sprintf(testAccAzureRMCdnEndpoint_withTags, ri, ri, ri) + postConfig := fmt.Sprintf(testAccAzureRMCdnEndpoint_withTagsUpdate, ri, ri, ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMCdnEndpointDestroy, + Steps: []resource.TestStep{ + { + Config: preConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMCdnEndpointExists("azurerm_cdn_endpoint.test"), + resource.TestCheckResourceAttr( + "azurerm_cdn_endpoint.test", "tags.#", "2"), + resource.TestCheckResourceAttr( + "azurerm_cdn_endpoint.test", "tags.environment", "Production"), + resource.TestCheckResourceAttr( + "azurerm_cdn_endpoint.test", "tags.cost_center", "MSFT"), + ), + }, + + { + Config: postConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMCdnEndpointExists("azurerm_cdn_endpoint.test"), + resource.TestCheckResourceAttr( + "azurerm_cdn_endpoint.test", "tags.#", "1"), + resource.TestCheckResourceAttr( + "azurerm_cdn_endpoint.test", "tags.environment", "staging"), + ), + }, + }, + }) +} + +func testCheckAzureRMCdnEndpointExists(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) + } + + name := rs.Primary.Attributes["name"] + profileName := rs.Primary.Attributes["profile_name"] + resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] + if !hasResourceGroup { + return fmt.Errorf("Bad: no resource group found in state for cdn endpoint: %s", name) + } + + conn := testAccProvider.Meta().(*ArmClient).cdnEndpointsClient + + resp, err := conn.Get(name, profileName, resourceGroup) + if err != nil { + return fmt.Errorf("Bad: Get on cdnEndpointsClient: %s", err) + } + + if resp.StatusCode == http.StatusNotFound { + return fmt.Errorf("Bad: CDN Endpoint %q (resource group: %q) does not exist", name, resourceGroup) + } + + return nil + } +} + +func testCheckAzureRMCdnEndpointDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*ArmClient).cdnEndpointsClient + + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_cdn_endpoint" { + continue + } + + name := rs.Primary.Attributes["name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] + profileName := rs.Primary.Attributes["profile_name"] + + resp, err := conn.Get(name, profileName, resourceGroup) + + if err != nil { + return nil + } + + if resp.StatusCode != http.StatusNotFound { + return fmt.Errorf("CDN Endpoint still exists:\n%#v", resp.Properties) + } + } + + return nil +} + +var testAccAzureRMCdnEndpoint_basic = ` +resource "azurerm_resource_group" "test" { + name = "acctestrg-%d" + location = "West US" +} +resource "azurerm_cdn_profile" "test" { + name = "acctestcdnprof%d" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + sku = "Standard" +} + +resource "azurerm_cdn_endpoint" "test" { + name = "acctestcdnend%d" + profile_name = "${azurerm_cdn_profile.test.name}" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + + origin { + name = "acceptanceTestCdnOrigin1" + host_name = "www.example.com" + https_port = 443 + http_port = 80 + } +} +` + +var testAccAzureRMCdnEndpoint_withTags = ` +resource "azurerm_resource_group" "test" { + name = "acctestrg-%d" + location = "West US" +} +resource "azurerm_cdn_profile" "test" { + name = "acctestcdnprof%d" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + sku = "Standard" +} + +resource "azurerm_cdn_endpoint" "test" { + name = "acctestcdnend%d" + profile_name = "${azurerm_cdn_profile.test.name}" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + + origin { + name = "acceptanceTestCdnOrigin2" + host_name = "www.example.com" + https_port = 443 + http_port = 80 + } + + tags { + environment = "Production" + cost_center = "MSFT" + } +} +` + +var testAccAzureRMCdnEndpoint_withTagsUpdate = ` +resource "azurerm_resource_group" "test" { + name = "acctestrg-%d" + location = "West US" +} +resource "azurerm_cdn_profile" "test" { + name = "acctestcdnprof%d" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + sku = "Standard" +} + +resource "azurerm_cdn_endpoint" "test" { + name = "acctestcdnend%d" + profile_name = "${azurerm_cdn_profile.test.name}" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + + origin { + name = "acceptanceTestCdnOrigin2" + host_name = "www.example.com" + https_port = 443 + http_port = 80 + } + + tags { + environment = "staging" + } +} +` diff --git a/builtin/providers/azurerm/resource_arm_cdn_profile.go b/builtin/providers/azurerm/resource_arm_cdn_profile.go index c3044b94090f..074f9b85586e 100644 --- a/builtin/providers/azurerm/resource_arm_cdn_profile.go +++ b/builtin/providers/azurerm/resource_arm_cdn_profile.go @@ -1,186 +1,171 @@ package azurerm -//import ( -// "fmt" -// "log" -// "net/http" -// "strings" -// "time" -// -// "github.com/Azure/azure-sdk-for-go/arm/cdn" -// "github.com/hashicorp/terraform/helper/resource" -// "github.com/hashicorp/terraform/helper/schema" -//) -// -//func resourceArmCdnProfile() *schema.Resource { -// return &schema.Resource{ -// Create: resourceArmCdnProfileCreate, -// Read: resourceArmCdnProfileRead, -// Update: resourceArmCdnProfileUpdate, -// Delete: resourceArmCdnProfileDelete, -// -// Schema: map[string]*schema.Schema{ -// "name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// }, -// -// "location": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// StateFunc: azureRMNormalizeLocation, -// }, -// -// "resource_group_name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// }, -// -// "sku": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// ValidateFunc: validateCdnProfileSku, -// }, -// -// "tags": tagsSchema(), -// }, -// } -//} -// -//func resourceArmCdnProfileCreate(d *schema.ResourceData, meta interface{}) error { -// client := meta.(*ArmClient) -// cdnProfilesClient := client.cdnProfilesClient -// -// log.Printf("[INFO] preparing arguments for Azure ARM CDN Profile creation.") -// -// name := d.Get("name").(string) -// location := d.Get("location").(string) -// resGroup := d.Get("resource_group_name").(string) -// sku := d.Get("sku").(string) -// tags := d.Get("tags").(map[string]interface{}) -// -// properties := cdn.ProfilePropertiesCreateParameters{ -// Sku: &cdn.Sku{ -// Name: cdn.SkuName(sku), -// }, -// } -// -// cdnProfile := cdn.ProfileCreateParameters{ -// Location: &location, -// Properties: &properties, -// Tags: expandTags(tags), -// } -// -// resp, err := cdnProfilesClient.Create(name, cdnProfile, resGroup) -// if err != nil { -// return err -// } -// -// d.SetId(*resp.ID) -// -// log.Printf("[DEBUG] Waiting for CDN Profile (%s) to become available", name) -// stateConf := &resource.StateChangeConf{ -// Pending: []string{"Accepted", "Updating", "Creating"}, -// Target: []string{"Succeeded"}, -// Refresh: cdnProfileStateRefreshFunc(client, resGroup, name), -// Timeout: 10 * time.Minute, -// } -// if _, err := stateConf.WaitForState(); err != nil { -// return fmt.Errorf("Error waiting for CDN Profile (%s) to become available: %s", name, err) -// } -// -// return resourceArmCdnProfileRead(d, meta) -//} -// -//func resourceArmCdnProfileRead(d *schema.ResourceData, meta interface{}) error { -// cdnProfilesClient := meta.(*ArmClient).cdnProfilesClient -// -// id, err := parseAzureResourceID(d.Id()) -// if err != nil { -// return err -// } -// resGroup := id.ResourceGroup -// name := id.Path["Profiles"] -// -// resp, err := cdnProfilesClient.Get(name, resGroup) -// if resp.StatusCode == http.StatusNotFound { -// d.SetId("") -// return nil -// } -// if err != nil { -// return fmt.Errorf("Error making Read request on Azure CDN Profile %s: %s", name, err) -// } -// -// if resp.Properties != nil && resp.Properties.Sku != nil { -// d.Set("sku", string(resp.Properties.Sku.Name)) -// } -// -// flattenAndSetTags(d, resp.Tags) -// -// return nil -//} -// -//func resourceArmCdnProfileUpdate(d *schema.ResourceData, meta interface{}) error { -// cdnProfilesClient := meta.(*ArmClient).cdnProfilesClient -// -// if !d.HasChange("tags") { -// return nil -// } -// -// name := d.Get("name").(string) -// resGroup := d.Get("resource_group_name").(string) -// newTags := d.Get("tags").(map[string]interface{}) -// -// props := cdn.ProfileUpdateParameters{ -// Tags: expandTags(newTags), -// } -// -// _, err := cdnProfilesClient.Update(name, props, resGroup) -// if err != nil { -// return fmt.Errorf("Error issuing Azure ARM update request to update CDN Profile %q: %s", name, err) -// } -// -// return resourceArmCdnProfileRead(d, meta) -//} -// -//func resourceArmCdnProfileDelete(d *schema.ResourceData, meta interface{}) error { -// cdnProfilesClient := meta.(*ArmClient).cdnProfilesClient -// -// id, err := parseAzureResourceID(d.Id()) -// if err != nil { -// return err -// } -// resGroup := id.ResourceGroup -// name := id.Path["Profiles"] -// -// _, err = cdnProfilesClient.DeleteIfExists(name, resGroup) -// -// return err -//} -// -//func cdnProfileStateRefreshFunc(client *ArmClient, resourceGroupName string, cdnProfileName string) resource.StateRefreshFunc { -// return func() (interface{}, string, error) { -// res, err := client.cdnProfilesClient.Get(cdnProfileName, resourceGroupName) -// if err != nil { -// return nil, "", fmt.Errorf("Error issuing read request in cdnProfileStateRefreshFunc to Azure ARM for CND Profile '%s' (RG: '%s'): %s", cdnProfileName, resourceGroupName, err) -// } -// return res, string(res.Properties.ProvisioningState), nil -// } -//} -// -//func validateCdnProfileSku(v interface{}, k string) (ws []string, errors []error) { -// value := strings.ToLower(v.(string)) -// skus := map[string]bool{ -// "standard": true, -// "premium": true, -// } -// -// if !skus[value] { -// errors = append(errors, fmt.Errorf("CDN Profile SKU can only be Standard or Premium")) -// } -// return -//} +import ( + "fmt" + "log" + "net/http" + "strings" + + "github.com/Azure/azure-sdk-for-go/arm/cdn" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceArmCdnProfile() *schema.Resource { + return &schema.Resource{ + Create: resourceArmCdnProfileCreate, + Read: resourceArmCdnProfileRead, + Update: resourceArmCdnProfileUpdate, + Delete: resourceArmCdnProfileDelete, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "location": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + StateFunc: azureRMNormalizeLocation, + }, + + "resource_group_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "sku": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validateCdnProfileSku, + }, + + "tags": tagsSchema(), + }, + } +} + +func resourceArmCdnProfileCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient) + cdnProfilesClient := client.cdnProfilesClient + + log.Printf("[INFO] preparing arguments for Azure ARM CDN Profile creation.") + + name := d.Get("name").(string) + location := d.Get("location").(string) + resGroup := d.Get("resource_group_name").(string) + sku := d.Get("sku").(string) + tags := d.Get("tags").(map[string]interface{}) + + properties := cdn.ProfilePropertiesCreateParameters{ + Sku: &cdn.Sku{ + Name: cdn.SkuName(sku), + }, + } + + cdnProfile := cdn.ProfileCreateParameters{ + Location: &location, + Properties: &properties, + Tags: expandTags(tags), + } + + _, err := cdnProfilesClient.Create(name, cdnProfile, resGroup, make(chan struct{})) + if err != nil { + return err + } + + read, err := cdnProfilesClient.Get(name, resGroup) + if err != nil { + return err + } + if read.ID == nil { + return fmt.Errorf("Cannot read CND Profile %s (resource group %s) ID", name, resGroup) + } + + d.SetId(*read.ID) + + return resourceArmCdnProfileRead(d, meta) +} + +func resourceArmCdnProfileRead(d *schema.ResourceData, meta interface{}) error { + cdnProfilesClient := meta.(*ArmClient).cdnProfilesClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + name := id.Path["Profiles"] + + resp, err := cdnProfilesClient.Get(name, resGroup) + if resp.StatusCode == http.StatusNotFound { + d.SetId("") + return nil + } + if err != nil { + return fmt.Errorf("Error making Read request on Azure CDN Profile %s: %s", name, err) + } + + if resp.Properties != nil && resp.Properties.Sku != nil { + d.Set("sku", string(resp.Properties.Sku.Name)) + } + + flattenAndSetTags(d, resp.Tags) + + return nil +} + +func resourceArmCdnProfileUpdate(d *schema.ResourceData, meta interface{}) error { + cdnProfilesClient := meta.(*ArmClient).cdnProfilesClient + + if !d.HasChange("tags") { + return nil + } + + name := d.Get("name").(string) + resGroup := d.Get("resource_group_name").(string) + newTags := d.Get("tags").(map[string]interface{}) + + props := cdn.ProfileUpdateParameters{ + Tags: expandTags(newTags), + } + + _, err := cdnProfilesClient.Update(name, props, resGroup) + if err != nil { + return fmt.Errorf("Error issuing Azure ARM update request to update CDN Profile %q: %s", name, err) + } + + return resourceArmCdnProfileRead(d, meta) +} + +func resourceArmCdnProfileDelete(d *schema.ResourceData, meta interface{}) error { + cdnProfilesClient := meta.(*ArmClient).cdnProfilesClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + name := id.Path["Profiles"] + + _, err = cdnProfilesClient.DeleteIfExists(name, resGroup, make(chan struct{})) + + return err +} + +func validateCdnProfileSku(v interface{}, k string) (ws []string, errors []error) { + value := strings.ToLower(v.(string)) + skus := map[string]bool{ + "standard": true, + "premium": true, + } + + if !skus[value] { + errors = append(errors, fmt.Errorf("CDN Profile SKU can only be Standard or Premium")) + } + return +} diff --git a/builtin/providers/azurerm/resource_arm_cdn_profile_test.go b/builtin/providers/azurerm/resource_arm_cdn_profile_test.go index c72c560b289e..aa16dbe21a02 100644 --- a/builtin/providers/azurerm/resource_arm_cdn_profile_test.go +++ b/builtin/providers/azurerm/resource_arm_cdn_profile_test.go @@ -1,207 +1,207 @@ 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 TestResourceAzureRMCdnProfileSKU_validation(t *testing.T) { -// cases := []struct { -// Value string -// ErrCount int -// }{ -// { -// Value: "Random", -// ErrCount: 1, -// }, -// { -// Value: "Standard", -// ErrCount: 0, -// }, -// { -// Value: "Premium", -// ErrCount: 0, -// }, -// { -// Value: "STANDARD", -// ErrCount: 0, -// }, -// { -// Value: "PREMIUM", -// ErrCount: 0, -// }, -// } -// -// for _, tc := range cases { -// _, errors := validateCdnProfileSku(tc.Value, "azurerm_cdn_profile") -// -// if len(errors) != tc.ErrCount { -// t.Fatalf("Expected the Azure RM CDN Profile SKU to trigger a validation error") -// } -// } -//} -// -//func TestAccAzureRMCdnProfile_basic(t *testing.T) { -// -// ri := acctest.RandInt() -// config := fmt.Sprintf(testAccAzureRMCdnProfile_basic, ri, ri) -// -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// Providers: testAccProviders, -// CheckDestroy: testCheckAzureRMCdnProfileDestroy, -// Steps: []resource.TestStep{ -// resource.TestStep{ -// Config: config, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMCdnProfileExists("azurerm_cdn_profile.test"), -// ), -// }, -// }, -// }) -//} -// -//func TestAccAzureRMCdnProfile_withTags(t *testing.T) { -// -// ri := acctest.RandInt() -// preConfig := fmt.Sprintf(testAccAzureRMCdnProfile_withTags, ri, ri) -// postConfig := fmt.Sprintf(testAccAzureRMCdnProfile_withTagsUpdate, ri, ri) -// -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// Providers: testAccProviders, -// CheckDestroy: testCheckAzureRMCdnProfileDestroy, -// Steps: []resource.TestStep{ -// resource.TestStep{ -// Config: preConfig, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMCdnProfileExists("azurerm_cdn_profile.test"), -// resource.TestCheckResourceAttr( -// "azurerm_cdn_profile.test", "tags.#", "2"), -// resource.TestCheckResourceAttr( -// "azurerm_cdn_profile.test", "tags.environment", "Production"), -// resource.TestCheckResourceAttr( -// "azurerm_cdn_profile.test", "tags.cost_center", "MSFT"), -// ), -// }, -// -// resource.TestStep{ -// Config: postConfig, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMCdnProfileExists("azurerm_cdn_profile.test"), -// resource.TestCheckResourceAttr( -// "azurerm_cdn_profile.test", "tags.#", "1"), -// resource.TestCheckResourceAttr( -// "azurerm_cdn_profile.test", "tags.environment", "staging"), -// ), -// }, -// }, -// }) -//} -// -//func testCheckAzureRMCdnProfileExists(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) -// } -// -// name := rs.Primary.Attributes["name"] -// resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] -// if !hasResourceGroup { -// return fmt.Errorf("Bad: no resource group found in state for cdn profile: %s", name) -// } -// -// conn := testAccProvider.Meta().(*ArmClient).cdnProfilesClient -// -// resp, err := conn.Get(name, resourceGroup) -// if err != nil { -// return fmt.Errorf("Bad: Get on cdnProfilesClient: %s", err) -// } -// -// if resp.StatusCode == http.StatusNotFound { -// return fmt.Errorf("Bad: CDN Profile %q (resource group: %q) does not exist", name, resourceGroup) -// } -// -// return nil -// } -//} -// -//func testCheckAzureRMCdnProfileDestroy(s *terraform.State) error { -// conn := testAccProvider.Meta().(*ArmClient).cdnProfilesClient -// -// for _, rs := range s.RootModule().Resources { -// if rs.Type != "azurerm_cdn_profile" { -// continue -// } -// -// name := rs.Primary.Attributes["name"] -// resourceGroup := rs.Primary.Attributes["resource_group_name"] -// -// resp, err := conn.Get(name, resourceGroup) -// -// if err != nil { -// return nil -// } -// -// if resp.StatusCode != http.StatusNotFound { -// return fmt.Errorf("CDN Profile still exists:\n%#v", resp.Properties) -// } -// } -// -// return nil -//} -// -//var testAccAzureRMCdnProfile_basic = ` -//resource "azurerm_resource_group" "test" { -// name = "acctestrg-%d" -// location = "West US" -//} -//resource "azurerm_cdn_profile" "test" { -// name = "acctestcdnprof%d" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// sku = "Standard" -//} -//` -// -//var testAccAzureRMCdnProfile_withTags = ` -//resource "azurerm_resource_group" "test" { -// name = "acctestrg-%d" -// location = "West US" -//} -//resource "azurerm_cdn_profile" "test" { -// name = "acctestcdnprof%d" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// sku = "Standard" -// -// tags { -// environment = "Production" -// cost_center = "MSFT" -// } -//} -//` -// -//var testAccAzureRMCdnProfile_withTagsUpdate = ` -//resource "azurerm_resource_group" "test" { -// name = "acctestrg-%d" -// location = "West US" -//} -//resource "azurerm_cdn_profile" "test" { -// name = "acctestcdnprof%d" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// sku = "Standard" -// -// tags { -// environment = "staging" -// } -//} -//` +import ( + "fmt" + "net/http" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestResourceAzureRMCdnProfileSKU_validation(t *testing.T) { + cases := []struct { + Value string + ErrCount int + }{ + { + Value: "Random", + ErrCount: 1, + }, + { + Value: "Standard", + ErrCount: 0, + }, + { + Value: "Premium", + ErrCount: 0, + }, + { + Value: "STANDARD", + ErrCount: 0, + }, + { + Value: "PREMIUM", + ErrCount: 0, + }, + } + + for _, tc := range cases { + _, errors := validateCdnProfileSku(tc.Value, "azurerm_cdn_profile") + + if len(errors) != tc.ErrCount { + t.Fatalf("Expected the Azure RM CDN Profile SKU to trigger a validation error") + } + } +} + +func TestAccAzureRMCdnProfile_basic(t *testing.T) { + + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMCdnProfile_basic, ri, ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMCdnProfileDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMCdnProfileExists("azurerm_cdn_profile.test"), + ), + }, + }, + }) +} + +func TestAccAzureRMCdnProfile_withTags(t *testing.T) { + + ri := acctest.RandInt() + preConfig := fmt.Sprintf(testAccAzureRMCdnProfile_withTags, ri, ri) + postConfig := fmt.Sprintf(testAccAzureRMCdnProfile_withTagsUpdate, ri, ri) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMCdnProfileDestroy, + Steps: []resource.TestStep{ + { + Config: preConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMCdnProfileExists("azurerm_cdn_profile.test"), + resource.TestCheckResourceAttr( + "azurerm_cdn_profile.test", "tags.#", "2"), + resource.TestCheckResourceAttr( + "azurerm_cdn_profile.test", "tags.environment", "Production"), + resource.TestCheckResourceAttr( + "azurerm_cdn_profile.test", "tags.cost_center", "MSFT"), + ), + }, + + { + Config: postConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMCdnProfileExists("azurerm_cdn_profile.test"), + resource.TestCheckResourceAttr( + "azurerm_cdn_profile.test", "tags.#", "1"), + resource.TestCheckResourceAttr( + "azurerm_cdn_profile.test", "tags.environment", "staging"), + ), + }, + }, + }) +} + +func testCheckAzureRMCdnProfileExists(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) + } + + name := rs.Primary.Attributes["name"] + resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] + if !hasResourceGroup { + return fmt.Errorf("Bad: no resource group found in state for cdn profile: %s", name) + } + + conn := testAccProvider.Meta().(*ArmClient).cdnProfilesClient + + resp, err := conn.Get(name, resourceGroup) + if err != nil { + return fmt.Errorf("Bad: Get on cdnProfilesClient: %s", err) + } + + if resp.StatusCode == http.StatusNotFound { + return fmt.Errorf("Bad: CDN Profile %q (resource group: %q) does not exist", name, resourceGroup) + } + + return nil + } +} + +func testCheckAzureRMCdnProfileDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*ArmClient).cdnProfilesClient + + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_cdn_profile" { + continue + } + + name := rs.Primary.Attributes["name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] + + resp, err := conn.Get(name, resourceGroup) + + if err != nil { + return nil + } + + if resp.StatusCode != http.StatusNotFound { + return fmt.Errorf("CDN Profile still exists:\n%#v", resp.Properties) + } + } + + return nil +} + +var testAccAzureRMCdnProfile_basic = ` +resource "azurerm_resource_group" "test" { + name = "acctestrg-%d" + location = "West US" +} +resource "azurerm_cdn_profile" "test" { + name = "acctestcdnprof%d" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + sku = "Standard" +} +` + +var testAccAzureRMCdnProfile_withTags = ` +resource "azurerm_resource_group" "test" { + name = "acctestrg-%d" + location = "West US" +} +resource "azurerm_cdn_profile" "test" { + name = "acctestcdnprof%d" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + sku = "Standard" + + tags { + environment = "Production" + cost_center = "MSFT" + } +} +` + +var testAccAzureRMCdnProfile_withTagsUpdate = ` +resource "azurerm_resource_group" "test" { + name = "acctestrg-%d" + location = "West US" +} +resource "azurerm_cdn_profile" "test" { + name = "acctestcdnprof%d" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + sku = "Standard" + + tags { + environment = "staging" + } +} +` From 738f4bd777e8a176880953f900106badc9b7675a Mon Sep 17 00:00:00 2001 From: James Nugent Date: Wed, 1 Jun 2016 19:51:57 -0500 Subject: [PATCH 16/17] provider/azurerm: Fix azurerm_virtual_machine --- builtin/providers/azurerm/provider.go | 4 +- .../azurerm/resource_arm_virtual_machine.go | 2229 ++++++++--------- .../resource_arm_virtual_machine_test.go | 1016 ++++---- 3 files changed, 1617 insertions(+), 1632 deletions(-) diff --git a/builtin/providers/azurerm/provider.go b/builtin/providers/azurerm/provider.go index 395359b439f2..58ff3d2565a1 100644 --- a/builtin/providers/azurerm/provider.go +++ b/builtin/providers/azurerm/provider.go @@ -61,8 +61,8 @@ func Provider() terraform.ResourceProvider { "azurerm_storage_queue": resourceArmStorageQueue(), "azurerm_subnet": resourceArmSubnet(), "azurerm_template_deployment": resourceArmTemplateDeployment(), - //"azurerm_virtual_machine": resourceArmVirtualMachine(), - "azurerm_virtual_network": resourceArmVirtualNetwork(), + "azurerm_virtual_machine": resourceArmVirtualMachine(), + "azurerm_virtual_network": resourceArmVirtualNetwork(), // These resources use the Riviera SDK "azurerm_dns_a_record": resourceArmDnsARecord(), diff --git a/builtin/providers/azurerm/resource_arm_virtual_machine.go b/builtin/providers/azurerm/resource_arm_virtual_machine.go index 78c30fdb7b4c..843e84c9be0d 100644 --- a/builtin/providers/azurerm/resource_arm_virtual_machine.go +++ b/builtin/providers/azurerm/resource_arm_virtual_machine.go @@ -1,597 +1,582 @@ package azurerm -//import ( -// "bytes" -// "fmt" -// "log" -// "net/http" -// "strings" -// "time" -// -// "github.com/Azure/azure-sdk-for-go/arm/compute" -// "github.com/hashicorp/terraform/helper/hashcode" -// "github.com/hashicorp/terraform/helper/resource" -// "github.com/hashicorp/terraform/helper/schema" -//) -// -//func resourceArmVirtualMachine() *schema.Resource { -// return &schema.Resource{ -// Create: resourceArmVirtualMachineCreate, -// Read: resourceArmVirtualMachineRead, -// Update: resourceArmVirtualMachineCreate, -// Delete: resourceArmVirtualMachineDelete, -// -// Schema: map[string]*schema.Schema{ -// "name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// }, -// -// "location": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// StateFunc: azureRMNormalizeLocation, -// }, -// -// "resource_group_name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// ForceNew: true, -// }, -// -// "plan": &schema.Schema{ -// Type: schema.TypeSet, -// Optional: true, -// Computed: true, -// Elem: &schema.Resource{ -// Schema: map[string]*schema.Schema{ -// "name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "publisher": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "product": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// }, -// }, -// Set: resourceArmVirtualMachinePlanHash, -// }, -// -// "availability_set_id": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// Computed: true, -// StateFunc: func(id interface{}) string { -// return strings.ToLower(id.(string)) -// }, -// }, -// -// "license_type": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// Computed: true, -// }, -// -// "vm_size": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "storage_image_reference": &schema.Schema{ -// Type: schema.TypeSet, -// Optional: true, -// Computed: true, -// Elem: &schema.Resource{ -// Schema: map[string]*schema.Schema{ -// "publisher": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "offer": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "sku": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "version": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// Computed: true, -// }, -// }, -// }, -// Set: resourceArmVirtualMachineStorageImageReferenceHash, -// }, -// -// "storage_os_disk": &schema.Schema{ -// Type: schema.TypeSet, -// Required: true, -// Elem: &schema.Resource{ -// Schema: map[string]*schema.Schema{ -// "os_type": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// }, -// -// "name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "vhd_uri": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "image_uri": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// }, -// -// "caching": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// Computed: true, -// }, -// -// "create_option": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// }, -// }, -// Set: resourceArmVirtualMachineStorageOsDiskHash, -// }, -// -// "storage_data_disk": &schema.Schema{ -// Type: schema.TypeList, -// Optional: true, -// Elem: &schema.Resource{ -// Schema: map[string]*schema.Schema{ -// "name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "vhd_uri": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "create_option": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "disk_size_gb": &schema.Schema{ -// Type: schema.TypeInt, -// Required: true, -// ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { -// value := v.(int) -// if value < 1 || value > 1023 { -// errors = append(errors, fmt.Errorf( -// "The `disk_size_gb` can only be between 1 and 1023")) -// } -// return -// }, -// }, -// -// "lun": &schema.Schema{ -// Type: schema.TypeInt, -// Required: true, -// }, -// }, -// }, -// }, -// -// "os_profile": &schema.Schema{ -// Type: schema.TypeSet, -// Required: true, -// Elem: &schema.Resource{ -// Schema: map[string]*schema.Schema{ -// "computer_name": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// Computed: true, -// }, -// -// "admin_username": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "admin_password": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "custom_data": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// Computed: true, -// }, -// }, -// }, -// Set: resourceArmVirtualMachineStorageOsProfileHash, -// }, -// -// "os_profile_windows_config": &schema.Schema{ -// Type: schema.TypeSet, -// Optional: true, -// Elem: &schema.Resource{ -// Schema: map[string]*schema.Schema{ -// "provision_vm_agent": &schema.Schema{ -// Type: schema.TypeBool, -// Optional: true, -// }, -// "enable_automatic_upgrades": &schema.Schema{ -// Type: schema.TypeBool, -// Optional: true, -// }, -// "winrm": &schema.Schema{ -// Type: schema.TypeSet, -// Optional: true, -// Elem: &schema.Resource{ -// Schema: map[string]*schema.Schema{ -// "protocol": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// "certificate_url": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// }, -// }, -// }, -// }, -// "additional_unattend_config": &schema.Schema{ -// Type: schema.TypeSet, -// Optional: true, -// Elem: &schema.Resource{ -// Schema: map[string]*schema.Schema{ -// "pass": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// "component": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// "setting_name": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// "content": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// }, -// }, -// }, -// }, -// }, -// Set: resourceArmVirtualMachineStorageOsProfileWindowsConfigHash, -// }, -// -// "os_profile_linux_config": &schema.Schema{ -// Type: schema.TypeSet, -// Optional: true, -// Elem: &schema.Resource{ -// Schema: map[string]*schema.Schema{ -// "disable_password_authentication": &schema.Schema{ -// Type: schema.TypeBool, -// Required: true, -// }, -// "ssh_keys": &schema.Schema{ -// Type: schema.TypeList, -// Optional: true, -// Elem: &schema.Resource{ -// Schema: map[string]*schema.Schema{ -// "path": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// "key_data": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// }, -// }, -// }, -// }, -// }, -// }, -// Set: resourceArmVirtualMachineStorageOsProfileLinuxConfigHash, -// }, -// -// "os_profile_secrets": &schema.Schema{ -// Type: schema.TypeSet, -// Optional: true, -// Elem: &schema.Resource{ -// Schema: map[string]*schema.Schema{ -// "source_vault_id": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// -// "vault_certificates": &schema.Schema{ -// Type: schema.TypeSet, -// Optional: true, -// Elem: &schema.Resource{ -// Schema: map[string]*schema.Schema{ -// "certificate_url": &schema.Schema{ -// Type: schema.TypeString, -// Required: true, -// }, -// "certificate_store": &schema.Schema{ -// Type: schema.TypeString, -// Optional: true, -// }, -// }, -// }, -// }, -// }, -// }, -// }, -// -// "network_interface_ids": &schema.Schema{ -// Type: schema.TypeSet, -// Required: true, -// Elem: &schema.Schema{Type: schema.TypeString}, -// Set: schema.HashString, -// }, -// -// "tags": tagsSchema(), -// }, -// } -//} -// -//func resourceArmVirtualMachineCreate(d *schema.ResourceData, meta interface{}) error { -// client := meta.(*ArmClient) -// vmClient := client.vmClient -// -// log.Printf("[INFO] preparing arguments for Azure ARM Virtual Machine creation.") -// -// name := d.Get("name").(string) -// location := d.Get("location").(string) -// resGroup := d.Get("resource_group_name").(string) -// tags := d.Get("tags").(map[string]interface{}) -// expandedTags := expandTags(tags) -// -// osDisk, err := expandAzureRmVirtualMachineOsDisk(d) -// if err != nil { -// return err -// } -// storageProfile := compute.StorageProfile{ -// OsDisk: osDisk, -// } -// -// if _, ok := d.GetOk("storage_image_reference"); ok { -// imageRef, err := expandAzureRmVirtualMachineImageReference(d) -// if err != nil { -// return err -// } -// storageProfile.ImageReference = imageRef -// } -// -// if _, ok := d.GetOk("storage_data_disk"); ok { -// dataDisks, err := expandAzureRmVirtualMachineDataDisk(d) -// if err != nil { -// return err -// } -// storageProfile.DataDisks = &dataDisks -// } -// -// networkProfile := expandAzureRmVirtualMachineNetworkProfile(d) -// vmSize := d.Get("vm_size").(string) -// properties := compute.VirtualMachineProperties{ -// NetworkProfile: &networkProfile, -// HardwareProfile: &compute.HardwareProfile{ -// VMSize: compute.VirtualMachineSizeTypes(vmSize), -// }, -// StorageProfile: &storageProfile, -// } -// -// osProfile, err := expandAzureRmVirtualMachineOsProfile(d) -// if err != nil { -// return err -// } -// properties.OsProfile = osProfile -// -// if v, ok := d.GetOk("availability_set_id"); ok { -// availabilitySet := v.(string) -// availSet := compute.SubResource{ -// ID: &availabilitySet, -// } -// -// properties.AvailabilitySet = &availSet -// } -// -// vm := compute.VirtualMachine{ -// Name: &name, -// Location: &location, -// Properties: &properties, -// Tags: expandedTags, -// } -// -// if _, ok := d.GetOk("plan"); ok { -// plan, err := expandAzureRmVirtualMachinePlan(d) -// if err != nil { -// return err -// } -// -// vm.Plan = plan -// } -// -// resp, vmErr := vmClient.CreateOrUpdate(resGroup, name, vm) -// if vmErr != nil { -// return vmErr -// } -// -// d.SetId(*resp.ID) -// -// log.Printf("[DEBUG] Waiting for Virtual Machine (%s) to become available", name) -// stateConf := &resource.StateChangeConf{ -// Pending: []string{"Creating", "Updating"}, -// Target: []string{"Succeeded"}, -// Refresh: virtualMachineStateRefreshFunc(client, resGroup, name), -// Timeout: 20 * time.Minute, -// MinTimeout: 10 * time.Second, -// } -// if _, err := stateConf.WaitForState(); err != nil { -// return fmt.Errorf("Error waiting for Virtual Machine (%s) to become available: %s", name, err) -// } -// -// return resourceArmVirtualMachineRead(d, meta) -//} -// -//func resourceArmVirtualMachineRead(d *schema.ResourceData, meta interface{}) error { -// vmClient := meta.(*ArmClient).vmClient -// -// id, err := parseAzureResourceID(d.Id()) -// if err != nil { -// return err -// } -// resGroup := id.ResourceGroup -// name := id.Path["virtualMachines"] -// -// resp, err := vmClient.Get(resGroup, name, "") -// if resp.StatusCode == http.StatusNotFound { -// d.SetId("") -// return nil -// } -// if err != nil { -// return fmt.Errorf("Error making Read request on Azure Virtual Machine %s: %s", name, err) -// } -// -// if resp.Plan != nil { -// if err := d.Set("plan", flattenAzureRmVirtualMachinePlan(resp.Plan)); err != nil { -// return fmt.Errorf("[DEBUG] Error setting Virtual Machine Plan error: %#v", err) -// } -// } -// -// if resp.Properties.AvailabilitySet != nil { -// d.Set("availability_set_id", strings.ToLower(*resp.Properties.AvailabilitySet.ID)) -// } -// -// d.Set("vm_size", resp.Properties.HardwareProfile.VMSize) -// -// if resp.Properties.StorageProfile.ImageReference != nil { -// if err := d.Set("storage_image_reference", schema.NewSet(resourceArmVirtualMachineStorageImageReferenceHash, flattenAzureRmVirtualMachineImageReference(resp.Properties.StorageProfile.ImageReference))); err != nil { -// return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage Image Reference error: %#v", err) -// } -// } -// -// if err := d.Set("storage_os_disk", schema.NewSet(resourceArmVirtualMachineStorageOsDiskHash, flattenAzureRmVirtualMachineOsDisk(resp.Properties.StorageProfile.OsDisk))); err != nil { -// return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage OS Disk error: %#v", err) -// } -// -// if resp.Properties.StorageProfile.DataDisks != nil { -// if err := d.Set("storage_data_disk", flattenAzureRmVirtualMachineDataDisk(resp.Properties.StorageProfile.DataDisks)); err != nil { -// return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage Data Disks error: %#v", err) -// } -// } -// -// if err := d.Set("os_profile", schema.NewSet(resourceArmVirtualMachineStorageOsProfileHash, flattenAzureRmVirtualMachineOsProfile(resp.Properties.OsProfile))); err != nil { -// return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage OS Profile: %#v", err) -// } -// -// if resp.Properties.OsProfile.WindowsConfiguration != nil { -// if err := d.Set("os_profile_windows_config", schema.NewSet(resourceArmVirtualMachineStorageOsProfileWindowsConfigHash, flattenAzureRmVirtualMachineOsProfileWindowsConfiguration(resp.Properties.OsProfile.WindowsConfiguration))); err != nil { -// return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage OS Profile Windows Configuration: %#v", err) -// } -// } -// -// if resp.Properties.OsProfile.LinuxConfiguration != nil { -// if err := d.Set("os_profile_linux_config", flattenAzureRmVirtualMachineOsProfileLinuxConfiguration(resp.Properties.OsProfile.LinuxConfiguration)); err != nil { -// return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage OS Profile Linux Configuration: %#v", err) -// } -// } -// -// if resp.Properties.OsProfile.Secrets != nil { -// if err := d.Set("os_profile_secrets", flattenAzureRmVirtualMachineOsProfileSecrets(resp.Properties.OsProfile.Secrets)); err != nil { -// return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage OS Profile Secrets: %#v", err) -// } -// } -// -// if resp.Properties.NetworkProfile != nil { -// if err := d.Set("network_interface_ids", flattenAzureRmVirtualMachineNetworkInterfaces(resp.Properties.NetworkProfile)); err != nil { -// return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage Network Interfaces: %#v", err) -// } -// } -// -// flattenAndSetTags(d, resp.Tags) -// -// return nil -//} -// -//func resourceArmVirtualMachineDelete(d *schema.ResourceData, meta interface{}) error { -// vmClient := meta.(*ArmClient).vmClient -// -// id, err := parseAzureResourceID(d.Id()) -// if err != nil { -// return err -// } -// resGroup := id.ResourceGroup -// name := id.Path["virtualMachines"] -// -// _, err = vmClient.Delete(resGroup, name) -// -// return err -//} -// -//func virtualMachineStateRefreshFunc(client *ArmClient, resourceGroupName string, vmName string) resource.StateRefreshFunc { -// return func() (interface{}, string, error) { -// res, err := client.vmClient.Get(resourceGroupName, vmName, "") -// if err != nil { -// return nil, "", fmt.Errorf("Error issuing read request in virtualMachineStateRefreshFunc to Azure ARM for Virtual Machine '%s' (RG: '%s'): %s", vmName, resourceGroupName, err) -// } -// -// return res, *res.Properties.ProvisioningState, nil -// } -//} -// -//func resourceArmVirtualMachinePlanHash(v interface{}) int { -// var buf bytes.Buffer -// m := v.(map[string]interface{}) -// buf.WriteString(fmt.Sprintf("%s-", m["name"].(string))) -// buf.WriteString(fmt.Sprintf("%s-", m["publisher"].(string))) -// buf.WriteString(fmt.Sprintf("%s-", m["product"].(string))) -// -// return hashcode.String(buf.String()) -//} -// -//func resourceArmVirtualMachineStorageImageReferenceHash(v interface{}) int { -// var buf bytes.Buffer -// m := v.(map[string]interface{}) -// buf.WriteString(fmt.Sprintf("%s-", m["publisher"].(string))) -// buf.WriteString(fmt.Sprintf("%s-", m["offer"].(string))) -// buf.WriteString(fmt.Sprintf("%s-", m["sku"].(string))) -// -// return hashcode.String(buf.String()) -//} -// -//func resourceArmVirtualMachineStorageOsProfileHash(v interface{}) int { -// var buf bytes.Buffer -// m := v.(map[string]interface{}) -// buf.WriteString(fmt.Sprintf("%s-", m["admin_username"].(string))) -// buf.WriteString(fmt.Sprintf("%s-", m["computer_name"].(string))) -// return hashcode.String(buf.String()) -//} -// +import ( + "bytes" + "fmt" + "log" + "net/http" + "strings" + + "github.com/Azure/azure-sdk-for-go/arm/compute" + "github.com/hashicorp/terraform/helper/hashcode" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceArmVirtualMachine() *schema.Resource { + return &schema.Resource{ + Create: resourceArmVirtualMachineCreate, + Read: resourceArmVirtualMachineRead, + Update: resourceArmVirtualMachineCreate, + Delete: resourceArmVirtualMachineDelete, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "location": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + StateFunc: azureRMNormalizeLocation, + }, + + "resource_group_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "plan": { + Type: schema.TypeSet, + Optional: true, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + }, + + "publisher": { + Type: schema.TypeString, + Required: true, + }, + + "product": { + Type: schema.TypeString, + Required: true, + }, + }, + }, + Set: resourceArmVirtualMachinePlanHash, + }, + + "availability_set_id": { + Type: schema.TypeString, + Optional: true, + Computed: true, + StateFunc: func(id interface{}) string { + return strings.ToLower(id.(string)) + }, + }, + + "license_type": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + + "vm_size": { + Type: schema.TypeString, + Required: true, + }, + + "storage_image_reference": { + Type: schema.TypeSet, + Optional: true, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "publisher": { + Type: schema.TypeString, + Required: true, + }, + + "offer": { + Type: schema.TypeString, + Required: true, + }, + + "sku": { + Type: schema.TypeString, + Required: true, + }, + + "version": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + }, + }, + Set: resourceArmVirtualMachineStorageImageReferenceHash, + }, + + "storage_os_disk": { + Type: schema.TypeSet, + Required: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "os_type": { + Type: schema.TypeString, + Optional: true, + }, + + "name": { + Type: schema.TypeString, + Required: true, + }, + + "vhd_uri": { + Type: schema.TypeString, + Required: true, + }, + + "image_uri": { + Type: schema.TypeString, + Optional: true, + }, + + "caching": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + + "create_option": { + Type: schema.TypeString, + Required: true, + }, + }, + }, + Set: resourceArmVirtualMachineStorageOsDiskHash, + }, + + "storage_data_disk": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + }, + + "vhd_uri": { + Type: schema.TypeString, + Required: true, + }, + + "create_option": { + Type: schema.TypeString, + Required: true, + }, + + "disk_size_gb": { + Type: schema.TypeInt, + Required: true, + ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { + value := v.(int) + if value < 1 || value > 1023 { + errors = append(errors, fmt.Errorf( + "The `disk_size_gb` can only be between 1 and 1023")) + } + return + }, + }, + + "lun": { + Type: schema.TypeInt, + Required: true, + }, + }, + }, + }, + + "os_profile": { + Type: schema.TypeSet, + Required: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "computer_name": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + + "admin_username": { + Type: schema.TypeString, + Required: true, + }, + + "admin_password": { + Type: schema.TypeString, + Required: true, + }, + + "custom_data": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + }, + }, + Set: resourceArmVirtualMachineStorageOsProfileHash, + }, + + "os_profile_windows_config": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "provision_vm_agent": { + Type: schema.TypeBool, + Optional: true, + }, + "enable_automatic_upgrades": { + Type: schema.TypeBool, + Optional: true, + }, + "winrm": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "protocol": { + Type: schema.TypeString, + Required: true, + }, + "certificate_url": { + Type: schema.TypeString, + Optional: true, + }, + }, + }, + }, + "additional_unattend_config": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "pass": { + Type: schema.TypeString, + Required: true, + }, + "component": { + Type: schema.TypeString, + Required: true, + }, + "setting_name": { + Type: schema.TypeString, + Required: true, + }, + "content": { + Type: schema.TypeString, + Required: true, + }, + }, + }, + }, + }, + }, + Set: resourceArmVirtualMachineStorageOsProfileWindowsConfigHash, + }, + + "os_profile_linux_config": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "disable_password_authentication": { + Type: schema.TypeBool, + Required: true, + }, + "ssh_keys": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "path": { + Type: schema.TypeString, + Required: true, + }, + "key_data": { + Type: schema.TypeString, + Optional: true, + }, + }, + }, + }, + }, + }, + Set: resourceArmVirtualMachineStorageOsProfileLinuxConfigHash, + }, + + "os_profile_secrets": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "source_vault_id": { + Type: schema.TypeString, + Required: true, + }, + + "vault_certificates": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "certificate_url": { + Type: schema.TypeString, + Required: true, + }, + "certificate_store": { + Type: schema.TypeString, + Optional: true, + }, + }, + }, + }, + }, + }, + }, + + "network_interface_ids": { + Type: schema.TypeSet, + Required: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Set: schema.HashString, + }, + + "tags": tagsSchema(), + }, + } +} + +func resourceArmVirtualMachineCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient) + vmClient := client.vmClient + + log.Printf("[INFO] preparing arguments for Azure ARM Virtual Machine creation.") + + name := d.Get("name").(string) + location := d.Get("location").(string) + resGroup := d.Get("resource_group_name").(string) + tags := d.Get("tags").(map[string]interface{}) + expandedTags := expandTags(tags) + + osDisk, err := expandAzureRmVirtualMachineOsDisk(d) + if err != nil { + return err + } + storageProfile := compute.StorageProfile{ + OsDisk: osDisk, + } + + if _, ok := d.GetOk("storage_image_reference"); ok { + imageRef, err := expandAzureRmVirtualMachineImageReference(d) + if err != nil { + return err + } + storageProfile.ImageReference = imageRef + } + + if _, ok := d.GetOk("storage_data_disk"); ok { + dataDisks, err := expandAzureRmVirtualMachineDataDisk(d) + if err != nil { + return err + } + storageProfile.DataDisks = &dataDisks + } + + networkProfile := expandAzureRmVirtualMachineNetworkProfile(d) + vmSize := d.Get("vm_size").(string) + properties := compute.VirtualMachineProperties{ + NetworkProfile: &networkProfile, + HardwareProfile: &compute.HardwareProfile{ + VMSize: compute.VirtualMachineSizeTypes(vmSize), + }, + StorageProfile: &storageProfile, + } + + osProfile, err := expandAzureRmVirtualMachineOsProfile(d) + if err != nil { + return err + } + properties.OsProfile = osProfile + + if v, ok := d.GetOk("availability_set_id"); ok { + availabilitySet := v.(string) + availSet := compute.SubResource{ + ID: &availabilitySet, + } + + properties.AvailabilitySet = &availSet + } + + vm := compute.VirtualMachine{ + Name: &name, + Location: &location, + Properties: &properties, + Tags: expandedTags, + } + + if _, ok := d.GetOk("plan"); ok { + plan, err := expandAzureRmVirtualMachinePlan(d) + if err != nil { + return err + } + + vm.Plan = plan + } + + _, vmErr := vmClient.CreateOrUpdate(resGroup, name, vm, make(chan struct{})) + if vmErr != nil { + return vmErr + } + + read, err := vmClient.Get(resGroup, name, "") + if err != nil { + return err + } + if read.ID == nil { + return fmt.Errorf("Cannot read Virtual Machine %s (resource group %s) ID", name, resGroup) + } + + d.SetId(*read.ID) + + return resourceArmVirtualMachineRead(d, meta) +} + +func resourceArmVirtualMachineRead(d *schema.ResourceData, meta interface{}) error { + vmClient := meta.(*ArmClient).vmClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + name := id.Path["virtualMachines"] + + resp, err := vmClient.Get(resGroup, name, "") + if resp.StatusCode == http.StatusNotFound { + d.SetId("") + return nil + } + if err != nil { + return fmt.Errorf("Error making Read request on Azure Virtual Machine %s: %s", name, err) + } + + if resp.Plan != nil { + if err := d.Set("plan", flattenAzureRmVirtualMachinePlan(resp.Plan)); err != nil { + return fmt.Errorf("[DEBUG] Error setting Virtual Machine Plan error: %#v", err) + } + } + + if resp.Properties.AvailabilitySet != nil { + d.Set("availability_set_id", strings.ToLower(*resp.Properties.AvailabilitySet.ID)) + } + + d.Set("vm_size", resp.Properties.HardwareProfile.VMSize) + + if resp.Properties.StorageProfile.ImageReference != nil { + if err := d.Set("storage_image_reference", schema.NewSet(resourceArmVirtualMachineStorageImageReferenceHash, flattenAzureRmVirtualMachineImageReference(resp.Properties.StorageProfile.ImageReference))); err != nil { + return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage Image Reference error: %#v", err) + } + } + + if err := d.Set("storage_os_disk", schema.NewSet(resourceArmVirtualMachineStorageOsDiskHash, flattenAzureRmVirtualMachineOsDisk(resp.Properties.StorageProfile.OsDisk))); err != nil { + return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage OS Disk error: %#v", err) + } + + if resp.Properties.StorageProfile.DataDisks != nil { + if err := d.Set("storage_data_disk", flattenAzureRmVirtualMachineDataDisk(resp.Properties.StorageProfile.DataDisks)); err != nil { + return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage Data Disks error: %#v", err) + } + } + + if err := d.Set("os_profile", schema.NewSet(resourceArmVirtualMachineStorageOsProfileHash, flattenAzureRmVirtualMachineOsProfile(resp.Properties.OsProfile))); err != nil { + return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage OS Profile: %#v", err) + } + + if resp.Properties.OsProfile.WindowsConfiguration != nil { + if err := d.Set("os_profile_windows_config", schema.NewSet(resourceArmVirtualMachineStorageOsProfileWindowsConfigHash, flattenAzureRmVirtualMachineOsProfileWindowsConfiguration(resp.Properties.OsProfile.WindowsConfiguration))); err != nil { + return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage OS Profile Windows Configuration: %#v", err) + } + } + + if resp.Properties.OsProfile.LinuxConfiguration != nil { + if err := d.Set("os_profile_linux_config", flattenAzureRmVirtualMachineOsProfileLinuxConfiguration(resp.Properties.OsProfile.LinuxConfiguration)); err != nil { + return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage OS Profile Linux Configuration: %#v", err) + } + } + + if resp.Properties.OsProfile.Secrets != nil { + if err := d.Set("os_profile_secrets", flattenAzureRmVirtualMachineOsProfileSecrets(resp.Properties.OsProfile.Secrets)); err != nil { + return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage OS Profile Secrets: %#v", err) + } + } + + if resp.Properties.NetworkProfile != nil { + if err := d.Set("network_interface_ids", flattenAzureRmVirtualMachineNetworkInterfaces(resp.Properties.NetworkProfile)); err != nil { + return fmt.Errorf("[DEBUG] Error setting Virtual Machine Storage Network Interfaces: %#v", err) + } + } + + flattenAndSetTags(d, resp.Tags) + + return nil +} + +func resourceArmVirtualMachineDelete(d *schema.ResourceData, meta interface{}) error { + vmClient := meta.(*ArmClient).vmClient + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + resGroup := id.ResourceGroup + name := id.Path["virtualMachines"] + + _, err = vmClient.Delete(resGroup, name, make(chan struct{})) + + return err +} + +func resourceArmVirtualMachinePlanHash(v interface{}) int { + var buf bytes.Buffer + m := v.(map[string]interface{}) + buf.WriteString(fmt.Sprintf("%s-", m["name"].(string))) + buf.WriteString(fmt.Sprintf("%s-", m["publisher"].(string))) + buf.WriteString(fmt.Sprintf("%s-", m["product"].(string))) + + return hashcode.String(buf.String()) +} + +func resourceArmVirtualMachineStorageImageReferenceHash(v interface{}) int { + var buf bytes.Buffer + m := v.(map[string]interface{}) + buf.WriteString(fmt.Sprintf("%s-", m["publisher"].(string))) + buf.WriteString(fmt.Sprintf("%s-", m["offer"].(string))) + buf.WriteString(fmt.Sprintf("%s-", m["sku"].(string))) + + return hashcode.String(buf.String()) +} + +func resourceArmVirtualMachineStorageOsProfileHash(v interface{}) int { + var buf bytes.Buffer + m := v.(map[string]interface{}) + buf.WriteString(fmt.Sprintf("%s-", m["admin_username"].(string))) + buf.WriteString(fmt.Sprintf("%s-", m["computer_name"].(string))) + return hashcode.String(buf.String()) +} + //func resourceArmVirtualMachineStorageDataDiskHash(v interface{}) int { // var buf bytes.Buffer // m := v.(map[string]interface{}) @@ -603,533 +588,533 @@ package azurerm // // return hashcode.String(buf.String()) //} -// -//func resourceArmVirtualMachineStorageOsDiskHash(v interface{}) int { -// var buf bytes.Buffer -// m := v.(map[string]interface{}) -// buf.WriteString(fmt.Sprintf("%s-", m["name"].(string))) -// buf.WriteString(fmt.Sprintf("%s-", m["vhd_uri"].(string))) -// -// return hashcode.String(buf.String()) -//} -// -//func resourceArmVirtualMachineStorageOsProfileLinuxConfigHash(v interface{}) int { -// var buf bytes.Buffer -// m := v.(map[string]interface{}) -// buf.WriteString(fmt.Sprintf("%t-", m["disable_password_authentication"].(bool))) -// -// return hashcode.String(buf.String()) -//} -// -//func resourceArmVirtualMachineStorageOsProfileWindowsConfigHash(v interface{}) int { -// var buf bytes.Buffer -// m := v.(map[string]interface{}) -// if m["provision_vm_agent"] != nil { -// buf.WriteString(fmt.Sprintf("%t-", m["provision_vm_agent"].(bool))) -// } -// if m["enable_automatic_upgrades"] != nil { -// buf.WriteString(fmt.Sprintf("%t-", m["enable_automatic_upgrades"].(bool))) -// } -// return hashcode.String(buf.String()) -//} -// -//func flattenAzureRmVirtualMachinePlan(plan *compute.Plan) map[string]interface{} { -// result := make(map[string]interface{}) -// result["name"] = *plan.Name -// result["publisher"] = *plan.Publisher -// result["product"] = *plan.Product -// -// return result -//} -// -//func flattenAzureRmVirtualMachineImageReference(image *compute.ImageReference) []interface{} { -// result := make(map[string]interface{}) -// result["offer"] = *image.Offer -// result["publisher"] = *image.Publisher -// result["sku"] = *image.Sku -// -// if image.Version != nil { -// result["version"] = *image.Version -// } -// -// return []interface{}{result} -//} -// -//func flattenAzureRmVirtualMachineNetworkInterfaces(profile *compute.NetworkProfile) []string { -// result := make([]string, 0, len(*profile.NetworkInterfaces)) -// for _, nic := range *profile.NetworkInterfaces { -// result = append(result, *nic.ID) -// } -// return result -//} -// -//func flattenAzureRmVirtualMachineOsProfileSecrets(secrets *[]compute.VaultSecretGroup) []map[string]interface{} { -// result := make([]map[string]interface{}, 0, len(*secrets)) -// for _, secret := range *secrets { -// s := map[string]interface{}{ -// "source_vault_id": *secret.SourceVault.ID, -// } -// -// if secret.VaultCertificates != nil { -// certs := make([]map[string]interface{}, 0, len(*secret.VaultCertificates)) -// for _, cert := range *secret.VaultCertificates { -// vaultCert := make(map[string]interface{}) -// vaultCert["certificate_url"] = *cert.CertificateURL -// -// if cert.CertificateStore != nil { -// vaultCert["certificate_store"] = *cert.CertificateStore -// } -// -// certs = append(certs, vaultCert) -// } -// -// s["vault_certificates"] = certs -// } -// -// result = append(result, s) -// } -// return result -//} -// -//func flattenAzureRmVirtualMachineDataDisk(disks *[]compute.DataDisk) interface{} { -// result := make([]interface{}, len(*disks)) -// for i, disk := range *disks { -// l := make(map[string]interface{}) -// l["name"] = *disk.Name -// l["vhd_uri"] = *disk.Vhd.URI -// l["create_option"] = disk.CreateOption -// l["disk_size_gb"] = *disk.DiskSizeGB -// l["lun"] = *disk.Lun -// -// result[i] = l -// } -// return result -//} -// -//func flattenAzureRmVirtualMachineOsProfile(osProfile *compute.OSProfile) []interface{} { -// result := make(map[string]interface{}) -// result["computer_name"] = *osProfile.ComputerName -// result["admin_username"] = *osProfile.AdminUsername -// if osProfile.CustomData != nil { -// result["custom_data"] = *osProfile.CustomData -// } -// -// return []interface{}{result} -//} -// -//func flattenAzureRmVirtualMachineOsProfileWindowsConfiguration(config *compute.WindowsConfiguration) []interface{} { -// result := make(map[string]interface{}) -// -// if config.ProvisionVMAgent != nil { -// result["provision_vm_agent"] = *config.ProvisionVMAgent -// } -// -// if config.EnableAutomaticUpdates != nil { -// result["enable_automatic_upgrades"] = *config.EnableAutomaticUpdates -// } -// -// if config.WinRM != nil { -// listeners := make([]map[string]interface{}, 0, len(*config.WinRM.Listeners)) -// for _, i := range *config.WinRM.Listeners { -// listener := make(map[string]interface{}) -// listener["protocol"] = i.Protocol -// -// if i.CertificateURL != nil { -// listener["certificate_url"] = *i.CertificateURL -// } -// -// listeners = append(listeners, listener) -// } -// -// result["winrm"] = listeners -// } -// -// if config.AdditionalUnattendContent != nil { -// content := make([]map[string]interface{}, 0, len(*config.AdditionalUnattendContent)) -// for _, i := range *config.AdditionalUnattendContent { -// c := make(map[string]interface{}) -// c["pass"] = i.PassName -// c["component"] = i.ComponentName -// c["setting_name"] = i.SettingName -// c["content"] = *i.Content -// -// content = append(content, c) -// } -// -// result["additional_unattend_config"] = content -// } -// -// return []interface{}{result} -//} -// -//func flattenAzureRmVirtualMachineOsProfileLinuxConfiguration(config *compute.LinuxConfiguration) []interface{} { -// -// result := make(map[string]interface{}) -// result["disable_password_authentication"] = *config.DisablePasswordAuthentication -// -// if config.SSH != nil && len(*config.SSH.PublicKeys) > 0 { -// ssh_keys := make([]map[string]interface{}, len(*config.SSH.PublicKeys)) -// for _, i := range *config.SSH.PublicKeys { -// key := make(map[string]interface{}) -// key["path"] = *i.Path -// -// if i.KeyData != nil { -// key["key_data"] = *i.KeyData -// } -// -// ssh_keys = append(ssh_keys, key) -// } -// -// result["ssh_keys"] = ssh_keys -// } -// -// return []interface{}{result} -//} -// -//func flattenAzureRmVirtualMachineOsDisk(disk *compute.OSDisk) []interface{} { -// result := make(map[string]interface{}) -// result["name"] = *disk.Name -// result["vhd_uri"] = *disk.Vhd.URI -// result["create_option"] = disk.CreateOption -// result["caching"] = disk.Caching -// -// return []interface{}{result} -//} -// -//func expandAzureRmVirtualMachinePlan(d *schema.ResourceData) (*compute.Plan, error) { -// planConfigs := d.Get("plan").(*schema.Set).List() -// -// if len(planConfigs) != 1 { -// return nil, fmt.Errorf("Cannot specify more than one plan.") -// } -// -// planConfig := planConfigs[0].(map[string]interface{}) -// -// publisher := planConfig["publisher"].(string) -// name := planConfig["name"].(string) -// product := planConfig["product"].(string) -// -// return &compute.Plan{ -// Publisher: &publisher, -// Name: &name, -// Product: &product, -// }, nil -//} -// -//func expandAzureRmVirtualMachineOsProfile(d *schema.ResourceData) (*compute.OSProfile, error) { -// osProfiles := d.Get("os_profile").(*schema.Set).List() -// -// if len(osProfiles) != 1 { -// return nil, fmt.Errorf("[ERROR] Only 1 OS Profile Can be specified for an Azure RM Virtual Machine") -// } -// -// osProfile := osProfiles[0].(map[string]interface{}) -// -// adminUsername := osProfile["admin_username"].(string) -// adminPassword := osProfile["admin_password"].(string) -// -// profile := &compute.OSProfile{ -// AdminUsername: &adminUsername, -// } -// -// if adminPassword != "" { -// profile.AdminPassword = &adminPassword -// } -// -// if _, ok := d.GetOk("os_profile_windows_config"); ok { -// winConfig, err := expandAzureRmVirtualMachineOsProfileWindowsConfig(d) -// if err != nil { -// return nil, err -// } -// if winConfig != nil { -// profile.WindowsConfiguration = winConfig -// } -// } -// -// if _, ok := d.GetOk("os_profile_linux_config"); ok { -// linuxConfig, err := expandAzureRmVirtualMachineOsProfileLinuxConfig(d) -// if err != nil { -// return nil, err -// } -// if linuxConfig != nil { -// profile.LinuxConfiguration = linuxConfig -// } -// } -// -// if _, ok := d.GetOk("os_profile_secrets"); ok { -// secrets := expandAzureRmVirtualMachineOsProfileSecrets(d) -// if secrets != nil { -// profile.Secrets = secrets -// } -// } -// -// if v := osProfile["computer_name"].(string); v != "" { -// profile.ComputerName = &v -// } -// if v := osProfile["custom_data"].(string); v != "" { -// profile.CustomData = &v -// } -// -// return profile, nil -//} -// -//func expandAzureRmVirtualMachineOsProfileSecrets(d *schema.ResourceData) *[]compute.VaultSecretGroup { -// secretsConfig := d.Get("os_profile_secrets").(*schema.Set).List() -// secrets := make([]compute.VaultSecretGroup, 0, len(secretsConfig)) -// -// for _, secretConfig := range secretsConfig { -// config := secretConfig.(map[string]interface{}) -// sourceVaultId := config["source_vault_id"].(string) -// -// vaultSecretGroup := compute.VaultSecretGroup{ -// SourceVault: &compute.SubResource{ -// ID: &sourceVaultId, -// }, -// } -// -// if v := config["vault_certificates"]; v != nil { -// certsConfig := v.(*schema.Set).List() -// certs := make([]compute.VaultCertificate, 0, len(certsConfig)) -// for _, certConfig := range certsConfig { -// config := certConfig.(map[string]interface{}) -// -// certUrl := config["certificate_url"].(string) -// cert := compute.VaultCertificate{ -// CertificateURL: &certUrl, -// } -// if v := config["certificate_store"].(string); v != "" { -// cert.CertificateStore = &v -// } -// -// certs = append(certs, cert) -// } -// vaultSecretGroup.VaultCertificates = &certs -// } -// -// secrets = append(secrets, vaultSecretGroup) -// } -// -// return &secrets -//} -// -//func expandAzureRmVirtualMachineOsProfileLinuxConfig(d *schema.ResourceData) (*compute.LinuxConfiguration, error) { -// osProfilesLinuxConfig := d.Get("os_profile_linux_config").(*schema.Set).List() -// -// if len(osProfilesLinuxConfig) != 1 { -// return nil, fmt.Errorf("[ERROR] Only 1 OS Profile Linux Config Can be specified for an Azure RM Virtual Machine") -// } -// -// linuxConfig := osProfilesLinuxConfig[0].(map[string]interface{}) -// disablePasswordAuth := linuxConfig["disable_password_authentication"].(bool) -// -// config := &compute.LinuxConfiguration{ -// DisablePasswordAuthentication: &disablePasswordAuth, -// } -// -// linuxKeys := linuxConfig["ssh_keys"].([]interface{}) -// sshPublicKeys := []compute.SSHPublicKey{} -// for _, key := range linuxKeys { -// -// sshKey, ok := key.(map[string]interface{}) -// if !ok { -// continue -// } -// path := sshKey["path"].(string) -// keyData := sshKey["key_data"].(string) -// -// sshPublicKey := compute.SSHPublicKey{ -// Path: &path, -// KeyData: &keyData, -// } -// -// sshPublicKeys = append(sshPublicKeys, sshPublicKey) -// } -// -// config.SSH = &compute.SSHConfiguration{ -// PublicKeys: &sshPublicKeys, -// } -// -// return config, nil -//} -// -//func expandAzureRmVirtualMachineOsProfileWindowsConfig(d *schema.ResourceData) (*compute.WindowsConfiguration, error) { -// osProfilesWindowsConfig := d.Get("os_profile_windows_config").(*schema.Set).List() -// -// if len(osProfilesWindowsConfig) != 1 { -// return nil, fmt.Errorf("[ERROR] Only 1 OS Profile Windows Config Can be specified for an Azure RM Virtual Machine") -// } -// -// osProfileConfig := osProfilesWindowsConfig[0].(map[string]interface{}) -// config := &compute.WindowsConfiguration{} -// -// if v := osProfileConfig["provision_vm_agent"]; v != nil { -// provision := v.(bool) -// config.ProvisionVMAgent = &provision -// } -// -// if v := osProfileConfig["enable_automatic_upgrades"]; v != nil { -// update := v.(bool) -// config.EnableAutomaticUpdates = &update -// } -// -// if v := osProfileConfig["winrm"]; v != nil { -// winRm := v.(*schema.Set).List() -// if len(winRm) > 0 { -// winRmListners := make([]compute.WinRMListener, 0, len(winRm)) -// for _, winRmConfig := range winRm { -// config := winRmConfig.(map[string]interface{}) -// -// protocol := config["protocol"].(string) -// winRmListner := compute.WinRMListener{ -// Protocol: compute.ProtocolTypes(protocol), -// } -// if v := config["certificate_url"].(string); v != "" { -// winRmListner.CertificateURL = &v -// } -// -// winRmListners = append(winRmListners, winRmListner) -// } -// config.WinRM = &compute.WinRMConfiguration{ -// Listeners: &winRmListners, -// } -// } -// } -// if v := osProfileConfig["additional_unattend_config"]; v != nil { -// additionalConfig := v.(*schema.Set).List() -// if len(additionalConfig) > 0 { -// additionalConfigContent := make([]compute.AdditionalUnattendContent, 0, len(additionalConfig)) -// for _, addConfig := range additionalConfig { -// config := addConfig.(map[string]interface{}) -// pass := config["pass"].(string) -// component := config["component"].(string) -// settingName := config["setting_name"].(string) -// content := config["content"].(string) -// -// addContent := compute.AdditionalUnattendContent{ -// PassName: compute.PassNames(pass), -// ComponentName: compute.ComponentNames(component), -// SettingName: compute.SettingNames(settingName), -// Content: &content, -// } -// -// additionalConfigContent = append(additionalConfigContent, addContent) -// } -// config.AdditionalUnattendContent = &additionalConfigContent -// } -// } -// return config, nil -//} -// -//func expandAzureRmVirtualMachineDataDisk(d *schema.ResourceData) ([]compute.DataDisk, error) { -// disks := d.Get("storage_data_disk").([]interface{}) -// data_disks := make([]compute.DataDisk, 0, len(disks)) -// for _, disk_config := range disks { -// config := disk_config.(map[string]interface{}) -// -// name := config["name"].(string) -// vhd := config["vhd_uri"].(string) -// createOption := config["create_option"].(string) -// lun := config["lun"].(int) -// disk_size := config["disk_size_gb"].(int) -// -// data_disk := compute.DataDisk{ -// Name: &name, -// Vhd: &compute.VirtualHardDisk{ -// URI: &vhd, -// }, -// Lun: &lun, -// DiskSizeGB: &disk_size, -// CreateOption: compute.DiskCreateOptionTypes(createOption), -// } -// -// data_disks = append(data_disks, data_disk) -// } -// -// return data_disks, nil -//} -// -//func expandAzureRmVirtualMachineImageReference(d *schema.ResourceData) (*compute.ImageReference, error) { -// storageImageRefs := d.Get("storage_image_reference").(*schema.Set).List() -// -// if len(storageImageRefs) != 1 { -// return nil, fmt.Errorf("Cannot specify more than one storage_image_reference.") -// } -// -// storageImageRef := storageImageRefs[0].(map[string]interface{}) -// -// publisher := storageImageRef["publisher"].(string) -// offer := storageImageRef["offer"].(string) -// sku := storageImageRef["sku"].(string) -// version := storageImageRef["version"].(string) -// -// return &compute.ImageReference{ -// Publisher: &publisher, -// Offer: &offer, -// Sku: &sku, -// Version: &version, -// }, nil -//} -// -//func expandAzureRmVirtualMachineNetworkProfile(d *schema.ResourceData) compute.NetworkProfile { -// nicIds := d.Get("network_interface_ids").(*schema.Set).List() -// network_interfaces := make([]compute.NetworkInterfaceReference, 0, len(nicIds)) -// -// network_profile := compute.NetworkProfile{} -// -// for _, nic := range nicIds { -// id := nic.(string) -// network_interface := compute.NetworkInterfaceReference{ -// ID: &id, -// } -// network_interfaces = append(network_interfaces, network_interface) -// } -// -// network_profile.NetworkInterfaces = &network_interfaces -// -// return network_profile -//} -// -//func expandAzureRmVirtualMachineOsDisk(d *schema.ResourceData) (*compute.OSDisk, error) { -// disks := d.Get("storage_os_disk").(*schema.Set).List() -// -// if len(disks) != 1 { -// return nil, fmt.Errorf("[ERROR] Only 1 OS Disk Can be specified for an Azure RM Virtual Machine") -// } -// -// disk := disks[0].(map[string]interface{}) -// -// name := disk["name"].(string) -// vhdURI := disk["vhd_uri"].(string) -// imageURI := disk["image_uri"].(string) -// createOption := disk["create_option"].(string) -// -// osDisk := &compute.OSDisk{ -// Name: &name, -// Vhd: &compute.VirtualHardDisk{ -// URI: &vhdURI, -// }, -// CreateOption: compute.DiskCreateOptionTypes(createOption), -// } -// -// if v := disk["image_uri"].(string); v != "" { -// osDisk.Image = &compute.VirtualHardDisk{ -// URI: &imageURI, -// } -// } -// -// if v := disk["os_type"].(string); v != "" { -// if v == "linux" { -// osDisk.OsType = compute.Linux -// } else if v == "windows" { -// osDisk.OsType = compute.Windows -// } else { -// return nil, fmt.Errorf("[ERROR] os_type must be 'linux' or 'windows'") -// } -// } -// -// if v := disk["caching"].(string); v != "" { -// osDisk.Caching = compute.CachingTypes(v) -// } -// -// return osDisk, nil -//} + +func resourceArmVirtualMachineStorageOsDiskHash(v interface{}) int { + var buf bytes.Buffer + m := v.(map[string]interface{}) + buf.WriteString(fmt.Sprintf("%s-", m["name"].(string))) + buf.WriteString(fmt.Sprintf("%s-", m["vhd_uri"].(string))) + + return hashcode.String(buf.String()) +} + +func resourceArmVirtualMachineStorageOsProfileLinuxConfigHash(v interface{}) int { + var buf bytes.Buffer + m := v.(map[string]interface{}) + buf.WriteString(fmt.Sprintf("%t-", m["disable_password_authentication"].(bool))) + + return hashcode.String(buf.String()) +} + +func resourceArmVirtualMachineStorageOsProfileWindowsConfigHash(v interface{}) int { + var buf bytes.Buffer + m := v.(map[string]interface{}) + if m["provision_vm_agent"] != nil { + buf.WriteString(fmt.Sprintf("%t-", m["provision_vm_agent"].(bool))) + } + if m["enable_automatic_upgrades"] != nil { + buf.WriteString(fmt.Sprintf("%t-", m["enable_automatic_upgrades"].(bool))) + } + return hashcode.String(buf.String()) +} + +func flattenAzureRmVirtualMachinePlan(plan *compute.Plan) map[string]interface{} { + result := make(map[string]interface{}) + result["name"] = *plan.Name + result["publisher"] = *plan.Publisher + result["product"] = *plan.Product + + return result +} + +func flattenAzureRmVirtualMachineImageReference(image *compute.ImageReference) []interface{} { + result := make(map[string]interface{}) + result["offer"] = *image.Offer + result["publisher"] = *image.Publisher + result["sku"] = *image.Sku + + if image.Version != nil { + result["version"] = *image.Version + } + + return []interface{}{result} +} + +func flattenAzureRmVirtualMachineNetworkInterfaces(profile *compute.NetworkProfile) []string { + result := make([]string, 0, len(*profile.NetworkInterfaces)) + for _, nic := range *profile.NetworkInterfaces { + result = append(result, *nic.ID) + } + return result +} + +func flattenAzureRmVirtualMachineOsProfileSecrets(secrets *[]compute.VaultSecretGroup) []map[string]interface{} { + result := make([]map[string]interface{}, 0, len(*secrets)) + for _, secret := range *secrets { + s := map[string]interface{}{ + "source_vault_id": *secret.SourceVault.ID, + } + + if secret.VaultCertificates != nil { + certs := make([]map[string]interface{}, 0, len(*secret.VaultCertificates)) + for _, cert := range *secret.VaultCertificates { + vaultCert := make(map[string]interface{}) + vaultCert["certificate_url"] = *cert.CertificateURL + + if cert.CertificateStore != nil { + vaultCert["certificate_store"] = *cert.CertificateStore + } + + certs = append(certs, vaultCert) + } + + s["vault_certificates"] = certs + } + + result = append(result, s) + } + return result +} + +func flattenAzureRmVirtualMachineDataDisk(disks *[]compute.DataDisk) interface{} { + result := make([]interface{}, len(*disks)) + for i, disk := range *disks { + l := make(map[string]interface{}) + l["name"] = *disk.Name + l["vhd_uri"] = *disk.Vhd.URI + l["create_option"] = disk.CreateOption + l["disk_size_gb"] = *disk.DiskSizeGB + l["lun"] = *disk.Lun + + result[i] = l + } + return result +} + +func flattenAzureRmVirtualMachineOsProfile(osProfile *compute.OSProfile) []interface{} { + result := make(map[string]interface{}) + result["computer_name"] = *osProfile.ComputerName + result["admin_username"] = *osProfile.AdminUsername + if osProfile.CustomData != nil { + result["custom_data"] = *osProfile.CustomData + } + + return []interface{}{result} +} + +func flattenAzureRmVirtualMachineOsProfileWindowsConfiguration(config *compute.WindowsConfiguration) []interface{} { + result := make(map[string]interface{}) + + if config.ProvisionVMAgent != nil { + result["provision_vm_agent"] = *config.ProvisionVMAgent + } + + if config.EnableAutomaticUpdates != nil { + result["enable_automatic_upgrades"] = *config.EnableAutomaticUpdates + } + + if config.WinRM != nil { + listeners := make([]map[string]interface{}, 0, len(*config.WinRM.Listeners)) + for _, i := range *config.WinRM.Listeners { + listener := make(map[string]interface{}) + listener["protocol"] = i.Protocol + + if i.CertificateURL != nil { + listener["certificate_url"] = *i.CertificateURL + } + + listeners = append(listeners, listener) + } + + result["winrm"] = listeners + } + + if config.AdditionalUnattendContent != nil { + content := make([]map[string]interface{}, 0, len(*config.AdditionalUnattendContent)) + for _, i := range *config.AdditionalUnattendContent { + c := make(map[string]interface{}) + c["pass"] = i.PassName + c["component"] = i.ComponentName + c["setting_name"] = i.SettingName + c["content"] = *i.Content + + content = append(content, c) + } + + result["additional_unattend_config"] = content + } + + return []interface{}{result} +} + +func flattenAzureRmVirtualMachineOsProfileLinuxConfiguration(config *compute.LinuxConfiguration) []interface{} { + + result := make(map[string]interface{}) + result["disable_password_authentication"] = *config.DisablePasswordAuthentication + + if config.SSH != nil && len(*config.SSH.PublicKeys) > 0 { + ssh_keys := make([]map[string]interface{}, len(*config.SSH.PublicKeys)) + for _, i := range *config.SSH.PublicKeys { + key := make(map[string]interface{}) + key["path"] = *i.Path + + if i.KeyData != nil { + key["key_data"] = *i.KeyData + } + + ssh_keys = append(ssh_keys, key) + } + + result["ssh_keys"] = ssh_keys + } + + return []interface{}{result} +} + +func flattenAzureRmVirtualMachineOsDisk(disk *compute.OSDisk) []interface{} { + result := make(map[string]interface{}) + result["name"] = *disk.Name + result["vhd_uri"] = *disk.Vhd.URI + result["create_option"] = disk.CreateOption + result["caching"] = disk.Caching + + return []interface{}{result} +} + +func expandAzureRmVirtualMachinePlan(d *schema.ResourceData) (*compute.Plan, error) { + planConfigs := d.Get("plan").(*schema.Set).List() + + if len(planConfigs) != 1 { + return nil, fmt.Errorf("Cannot specify more than one plan.") + } + + planConfig := planConfigs[0].(map[string]interface{}) + + publisher := planConfig["publisher"].(string) + name := planConfig["name"].(string) + product := planConfig["product"].(string) + + return &compute.Plan{ + Publisher: &publisher, + Name: &name, + Product: &product, + }, nil +} + +func expandAzureRmVirtualMachineOsProfile(d *schema.ResourceData) (*compute.OSProfile, error) { + osProfiles := d.Get("os_profile").(*schema.Set).List() + + if len(osProfiles) != 1 { + return nil, fmt.Errorf("[ERROR] Only 1 OS Profile Can be specified for an Azure RM Virtual Machine") + } + + osProfile := osProfiles[0].(map[string]interface{}) + + adminUsername := osProfile["admin_username"].(string) + adminPassword := osProfile["admin_password"].(string) + + profile := &compute.OSProfile{ + AdminUsername: &adminUsername, + } + + if adminPassword != "" { + profile.AdminPassword = &adminPassword + } + + if _, ok := d.GetOk("os_profile_windows_config"); ok { + winConfig, err := expandAzureRmVirtualMachineOsProfileWindowsConfig(d) + if err != nil { + return nil, err + } + if winConfig != nil { + profile.WindowsConfiguration = winConfig + } + } + + if _, ok := d.GetOk("os_profile_linux_config"); ok { + linuxConfig, err := expandAzureRmVirtualMachineOsProfileLinuxConfig(d) + if err != nil { + return nil, err + } + if linuxConfig != nil { + profile.LinuxConfiguration = linuxConfig + } + } + + if _, ok := d.GetOk("os_profile_secrets"); ok { + secrets := expandAzureRmVirtualMachineOsProfileSecrets(d) + if secrets != nil { + profile.Secrets = secrets + } + } + + if v := osProfile["computer_name"].(string); v != "" { + profile.ComputerName = &v + } + if v := osProfile["custom_data"].(string); v != "" { + profile.CustomData = &v + } + + return profile, nil +} + +func expandAzureRmVirtualMachineOsProfileSecrets(d *schema.ResourceData) *[]compute.VaultSecretGroup { + secretsConfig := d.Get("os_profile_secrets").(*schema.Set).List() + secrets := make([]compute.VaultSecretGroup, 0, len(secretsConfig)) + + for _, secretConfig := range secretsConfig { + config := secretConfig.(map[string]interface{}) + sourceVaultId := config["source_vault_id"].(string) + + vaultSecretGroup := compute.VaultSecretGroup{ + SourceVault: &compute.SubResource{ + ID: &sourceVaultId, + }, + } + + if v := config["vault_certificates"]; v != nil { + certsConfig := v.(*schema.Set).List() + certs := make([]compute.VaultCertificate, 0, len(certsConfig)) + for _, certConfig := range certsConfig { + config := certConfig.(map[string]interface{}) + + certUrl := config["certificate_url"].(string) + cert := compute.VaultCertificate{ + CertificateURL: &certUrl, + } + if v := config["certificate_store"].(string); v != "" { + cert.CertificateStore = &v + } + + certs = append(certs, cert) + } + vaultSecretGroup.VaultCertificates = &certs + } + + secrets = append(secrets, vaultSecretGroup) + } + + return &secrets +} + +func expandAzureRmVirtualMachineOsProfileLinuxConfig(d *schema.ResourceData) (*compute.LinuxConfiguration, error) { + osProfilesLinuxConfig := d.Get("os_profile_linux_config").(*schema.Set).List() + + if len(osProfilesLinuxConfig) != 1 { + return nil, fmt.Errorf("[ERROR] Only 1 OS Profile Linux Config Can be specified for an Azure RM Virtual Machine") + } + + linuxConfig := osProfilesLinuxConfig[0].(map[string]interface{}) + disablePasswordAuth := linuxConfig["disable_password_authentication"].(bool) + + config := &compute.LinuxConfiguration{ + DisablePasswordAuthentication: &disablePasswordAuth, + } + + linuxKeys := linuxConfig["ssh_keys"].([]interface{}) + sshPublicKeys := []compute.SSHPublicKey{} + for _, key := range linuxKeys { + + sshKey, ok := key.(map[string]interface{}) + if !ok { + continue + } + path := sshKey["path"].(string) + keyData := sshKey["key_data"].(string) + + sshPublicKey := compute.SSHPublicKey{ + Path: &path, + KeyData: &keyData, + } + + sshPublicKeys = append(sshPublicKeys, sshPublicKey) + } + + config.SSH = &compute.SSHConfiguration{ + PublicKeys: &sshPublicKeys, + } + + return config, nil +} + +func expandAzureRmVirtualMachineOsProfileWindowsConfig(d *schema.ResourceData) (*compute.WindowsConfiguration, error) { + osProfilesWindowsConfig := d.Get("os_profile_windows_config").(*schema.Set).List() + + if len(osProfilesWindowsConfig) != 1 { + return nil, fmt.Errorf("[ERROR] Only 1 OS Profile Windows Config Can be specified for an Azure RM Virtual Machine") + } + + osProfileConfig := osProfilesWindowsConfig[0].(map[string]interface{}) + config := &compute.WindowsConfiguration{} + + if v := osProfileConfig["provision_vm_agent"]; v != nil { + provision := v.(bool) + config.ProvisionVMAgent = &provision + } + + if v := osProfileConfig["enable_automatic_upgrades"]; v != nil { + update := v.(bool) + config.EnableAutomaticUpdates = &update + } + + if v := osProfileConfig["winrm"]; v != nil { + winRm := v.(*schema.Set).List() + if len(winRm) > 0 { + winRmListners := make([]compute.WinRMListener, 0, len(winRm)) + for _, winRmConfig := range winRm { + config := winRmConfig.(map[string]interface{}) + + protocol := config["protocol"].(string) + winRmListner := compute.WinRMListener{ + Protocol: compute.ProtocolTypes(protocol), + } + if v := config["certificate_url"].(string); v != "" { + winRmListner.CertificateURL = &v + } + + winRmListners = append(winRmListners, winRmListner) + } + config.WinRM = &compute.WinRMConfiguration{ + Listeners: &winRmListners, + } + } + } + if v := osProfileConfig["additional_unattend_config"]; v != nil { + additionalConfig := v.(*schema.Set).List() + if len(additionalConfig) > 0 { + additionalConfigContent := make([]compute.AdditionalUnattendContent, 0, len(additionalConfig)) + for _, addConfig := range additionalConfig { + config := addConfig.(map[string]interface{}) + pass := config["pass"].(string) + component := config["component"].(string) + settingName := config["setting_name"].(string) + content := config["content"].(string) + + addContent := compute.AdditionalUnattendContent{ + PassName: compute.PassNames(pass), + ComponentName: compute.ComponentNames(component), + SettingName: compute.SettingNames(settingName), + Content: &content, + } + + additionalConfigContent = append(additionalConfigContent, addContent) + } + config.AdditionalUnattendContent = &additionalConfigContent + } + } + return config, nil +} + +func expandAzureRmVirtualMachineDataDisk(d *schema.ResourceData) ([]compute.DataDisk, error) { + disks := d.Get("storage_data_disk").([]interface{}) + data_disks := make([]compute.DataDisk, 0, len(disks)) + for _, disk_config := range disks { + config := disk_config.(map[string]interface{}) + + name := config["name"].(string) + vhd := config["vhd_uri"].(string) + createOption := config["create_option"].(string) + lun := int32(config["lun"].(int)) + disk_size := int32(config["disk_size_gb"].(int)) + + data_disk := compute.DataDisk{ + Name: &name, + Vhd: &compute.VirtualHardDisk{ + URI: &vhd, + }, + Lun: &lun, + DiskSizeGB: &disk_size, + CreateOption: compute.DiskCreateOptionTypes(createOption), + } + + data_disks = append(data_disks, data_disk) + } + + return data_disks, nil +} + +func expandAzureRmVirtualMachineImageReference(d *schema.ResourceData) (*compute.ImageReference, error) { + storageImageRefs := d.Get("storage_image_reference").(*schema.Set).List() + + if len(storageImageRefs) != 1 { + return nil, fmt.Errorf("Cannot specify more than one storage_image_reference.") + } + + storageImageRef := storageImageRefs[0].(map[string]interface{}) + + publisher := storageImageRef["publisher"].(string) + offer := storageImageRef["offer"].(string) + sku := storageImageRef["sku"].(string) + version := storageImageRef["version"].(string) + + return &compute.ImageReference{ + Publisher: &publisher, + Offer: &offer, + Sku: &sku, + Version: &version, + }, nil +} + +func expandAzureRmVirtualMachineNetworkProfile(d *schema.ResourceData) compute.NetworkProfile { + nicIds := d.Get("network_interface_ids").(*schema.Set).List() + network_interfaces := make([]compute.NetworkInterfaceReference, 0, len(nicIds)) + + network_profile := compute.NetworkProfile{} + + for _, nic := range nicIds { + id := nic.(string) + network_interface := compute.NetworkInterfaceReference{ + ID: &id, + } + network_interfaces = append(network_interfaces, network_interface) + } + + network_profile.NetworkInterfaces = &network_interfaces + + return network_profile +} + +func expandAzureRmVirtualMachineOsDisk(d *schema.ResourceData) (*compute.OSDisk, error) { + disks := d.Get("storage_os_disk").(*schema.Set).List() + + if len(disks) != 1 { + return nil, fmt.Errorf("[ERROR] Only 1 OS Disk Can be specified for an Azure RM Virtual Machine") + } + + disk := disks[0].(map[string]interface{}) + + name := disk["name"].(string) + vhdURI := disk["vhd_uri"].(string) + imageURI := disk["image_uri"].(string) + createOption := disk["create_option"].(string) + + osDisk := &compute.OSDisk{ + Name: &name, + Vhd: &compute.VirtualHardDisk{ + URI: &vhdURI, + }, + CreateOption: compute.DiskCreateOptionTypes(createOption), + } + + if v := disk["image_uri"].(string); v != "" { + osDisk.Image = &compute.VirtualHardDisk{ + URI: &imageURI, + } + } + + if v := disk["os_type"].(string); v != "" { + if v == "linux" { + osDisk.OsType = compute.Linux + } else if v == "windows" { + osDisk.OsType = compute.Windows + } else { + return nil, fmt.Errorf("[ERROR] os_type must be 'linux' or 'windows'") + } + } + + if v := disk["caching"].(string); v != "" { + osDisk.Caching = compute.CachingTypes(v) + } + + return osDisk, nil +} diff --git a/builtin/providers/azurerm/resource_arm_virtual_machine_test.go b/builtin/providers/azurerm/resource_arm_virtual_machine_test.go index 099de061df0f..81f6c25973d7 100644 --- a/builtin/providers/azurerm/resource_arm_virtual_machine_test.go +++ b/builtin/providers/azurerm/resource_arm_virtual_machine_test.go @@ -1,510 +1,510 @@ 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 TestAccAzureRMVirtualMachine_basicLinuxMachine(t *testing.T) { -// ri := acctest.RandInt() -// config := fmt.Sprintf(testAccAzureRMVirtualMachine_basicLinuxMachine, ri, ri, ri, ri, ri, ri, ri) -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// Providers: testAccProviders, -// CheckDestroy: testCheckAzureRMVirtualMachineDestroy, -// Steps: []resource.TestStep{ -// resource.TestStep{ -// Config: config, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test"), -// ), -// }, -// }, -// }) -//} -// -//func TestAccAzureRMVirtualMachine_tags(t *testing.T) { -// ri := acctest.RandInt() -// preConfig := fmt.Sprintf(testAccAzureRMVirtualMachine_basicLinuxMachine, ri, ri, ri, ri, ri, ri, ri) -// postConfig := fmt.Sprintf(testAccAzureRMVirtualMachine_basicLinuxMachineUpdated, ri, ri, ri, ri, ri, ri, ri) -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// Providers: testAccProviders, -// CheckDestroy: testCheckAzureRMVirtualMachineDestroy, -// Steps: []resource.TestStep{ -// resource.TestStep{ -// Config: preConfig, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test"), -// resource.TestCheckResourceAttr( -// "azurerm_virtual_machine.test", "tags.#", "2"), -// resource.TestCheckResourceAttr( -// "azurerm_virtual_machine.test", "tags.environment", "Production"), -// resource.TestCheckResourceAttr( -// "azurerm_virtual_machine.test", "tags.cost-center", "Ops"), -// ), -// }, -// -// resource.TestStep{ -// Config: postConfig, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test"), -// resource.TestCheckResourceAttr( -// "azurerm_virtual_machine.test", "tags.#", "1"), -// resource.TestCheckResourceAttr( -// "azurerm_virtual_machine.test", "tags.environment", "Production"), -// ), -// }, -// }, -// }) -//} -// -////This is a regression test around https://github.com/hashicorp/terraform/issues/6517 -////Because we use CreateOrUpdate, we were sending an empty password on update requests -//func TestAccAzureRMVirtualMachine_updateMachineSize(t *testing.T) { -// ri := acctest.RandInt() -// preConfig := fmt.Sprintf(testAccAzureRMVirtualMachine_basicLinuxMachine, ri, ri, ri, ri, ri, ri, ri) -// postConfig := fmt.Sprintf(testAccAzureRMVirtualMachine_updatedLinuxMachine, ri, ri, ri, ri, ri, ri, ri) -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// Providers: testAccProviders, -// CheckDestroy: testCheckAzureRMVirtualMachineDestroy, -// Steps: []resource.TestStep{ -// resource.TestStep{ -// Config: preConfig, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test"), -// resource.TestCheckResourceAttr( -// "azurerm_virtual_machine.test", "vm_size", "Standard_A0"), -// ), -// }, -// resource.TestStep{ -// Config: postConfig, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test"), -// resource.TestCheckResourceAttr( -// "azurerm_virtual_machine.test", "vm_size", "Standard_A1"), -// ), -// }, -// }, -// }) -//} -// -//func TestAccAzureRMVirtualMachine_basicWindowsMachine(t *testing.T) { -// ri := acctest.RandInt() -// config := fmt.Sprintf(testAccAzureRMVirtualMachine_basicWindowsMachine, ri, ri, ri, ri, ri, ri) -// resource.Test(t, resource.TestCase{ -// PreCheck: func() { testAccPreCheck(t) }, -// Providers: testAccProviders, -// CheckDestroy: testCheckAzureRMVirtualMachineDestroy, -// Steps: []resource.TestStep{ -// resource.TestStep{ -// Config: config, -// Check: resource.ComposeTestCheckFunc( -// testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test"), -// ), -// }, -// }, -// }) -//} -// -//func testCheckAzureRMVirtualMachineExists(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) -// } -// -// vmName := rs.Primary.Attributes["name"] -// resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] -// if !hasResourceGroup { -// return fmt.Errorf("Bad: no resource group found in state for virtual machine: %s", vmName) -// } -// -// conn := testAccProvider.Meta().(*ArmClient).vmClient -// -// resp, err := conn.Get(resourceGroup, vmName, "") -// if err != nil { -// return fmt.Errorf("Bad: Get on vmClient: %s", err) -// } -// -// if resp.StatusCode == http.StatusNotFound { -// return fmt.Errorf("Bad: VirtualMachine %q (resource group: %q) does not exist", vmName, resourceGroup) -// } -// -// return nil -// } -//} -// -//func testCheckAzureRMVirtualMachineDestroy(s *terraform.State) error { -// conn := testAccProvider.Meta().(*ArmClient).vmClient -// -// for _, rs := range s.RootModule().Resources { -// if rs.Type != "azurerm_virtual_machine" { -// continue -// } -// -// name := rs.Primary.Attributes["name"] -// resourceGroup := rs.Primary.Attributes["resource_group_name"] -// -// resp, err := conn.Get(resourceGroup, name, "") -// -// if err != nil { -// return nil -// } -// -// if resp.StatusCode != http.StatusNotFound { -// return fmt.Errorf("Virtual Machine still exists:\n%#v", resp.Properties) -// } -// } -// -// return nil -//} -// -//var testAccAzureRMVirtualMachine_basicLinuxMachine = ` -//resource "azurerm_resource_group" "test" { -// name = "acctestrg-%d" -// location = "West US" -//} -// -//resource "azurerm_virtual_network" "test" { -// name = "acctvn-%d" -// address_space = ["10.0.0.0/16"] -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -//} -// -//resource "azurerm_subnet" "test" { -// name = "acctsub-%d" -// resource_group_name = "${azurerm_resource_group.test.name}" -// virtual_network_name = "${azurerm_virtual_network.test.name}" -// address_prefix = "10.0.2.0/24" -//} -// -//resource "azurerm_network_interface" "test" { -// name = "acctni-%d" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// -// ip_configuration { -// name = "testconfiguration1" -// subnet_id = "${azurerm_subnet.test.id}" -// private_ip_address_allocation = "dynamic" -// } -//} -// -//resource "azurerm_storage_account" "test" { -// name = "accsa%d" -// resource_group_name = "${azurerm_resource_group.test.name}" -// location = "westus" -// account_type = "Standard_LRS" -// -// tags { -// environment = "staging" -// } -//} -// -//resource "azurerm_storage_container" "test" { -// name = "vhds" -// resource_group_name = "${azurerm_resource_group.test.name}" -// storage_account_name = "${azurerm_storage_account.test.name}" -// container_access_type = "private" -//} -// -//resource "azurerm_virtual_machine" "test" { -// name = "acctvm-%d" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// network_interface_ids = ["${azurerm_network_interface.test.id}"] -// vm_size = "Standard_A0" -// -// storage_image_reference { -// publisher = "Canonical" -// offer = "UbuntuServer" -// sku = "14.04.2-LTS" -// version = "latest" -// } -// -// storage_os_disk { -// name = "myosdisk1" -// vhd_uri = "${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/myosdisk1.vhd" -// caching = "ReadWrite" -// create_option = "FromImage" -// } -// -// os_profile { -// computer_name = "hostname%d" -// admin_username = "testadmin" -// admin_password = "Password1234!" -// } -// -// os_profile_linux_config { -// disable_password_authentication = false -// } -// -// tags { -// environment = "Production" -// cost-center = "Ops" -// } -//} -//` -// -//var testAccAzureRMVirtualMachine_basicLinuxMachineUpdated = ` -//resource "azurerm_resource_group" "test" { -// name = "acctestrg-%d" -// location = "West US" -//} -// -//resource "azurerm_virtual_network" "test" { -// name = "acctvn-%d" -// address_space = ["10.0.0.0/16"] -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -//} -// -//resource "azurerm_subnet" "test" { -// name = "acctsub-%d" -// resource_group_name = "${azurerm_resource_group.test.name}" -// virtual_network_name = "${azurerm_virtual_network.test.name}" -// address_prefix = "10.0.2.0/24" -//} -// -//resource "azurerm_network_interface" "test" { -// name = "acctni-%d" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// -// ip_configuration { -// name = "testconfiguration1" -// subnet_id = "${azurerm_subnet.test.id}" -// private_ip_address_allocation = "dynamic" -// } -//} -// -//resource "azurerm_storage_account" "test" { -// name = "accsa%d" -// resource_group_name = "${azurerm_resource_group.test.name}" -// location = "westus" -// account_type = "Standard_LRS" -// -// tags { -// environment = "staging" -// } -//} -// -//resource "azurerm_storage_container" "test" { -// name = "vhds" -// resource_group_name = "${azurerm_resource_group.test.name}" -// storage_account_name = "${azurerm_storage_account.test.name}" -// container_access_type = "private" -//} -// -//resource "azurerm_virtual_machine" "test" { -// name = "acctvm-%d" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// network_interface_ids = ["${azurerm_network_interface.test.id}"] -// vm_size = "Standard_A0" -// -// storage_image_reference { -// publisher = "Canonical" -// offer = "UbuntuServer" -// sku = "14.04.2-LTS" -// version = "latest" -// } -// -// storage_os_disk { -// name = "myosdisk1" -// vhd_uri = "${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/myosdisk1.vhd" -// caching = "ReadWrite" -// create_option = "FromImage" -// } -// -// os_profile { -// computer_name = "hostname%d" -// admin_username = "testadmin" -// admin_password = "Password1234!" -// } -// -// os_profile_linux_config { -// disable_password_authentication = false -// } -// -// tags { -// environment = "Production" -// } -//} -//` -// -//var testAccAzureRMVirtualMachine_updatedLinuxMachine = ` -//resource "azurerm_resource_group" "test" { -// name = "acctestrg-%d" -// location = "West US" -//} -// -//resource "azurerm_virtual_network" "test" { -// name = "acctvn-%d" -// address_space = ["10.0.0.0/16"] -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -//} -// -//resource "azurerm_subnet" "test" { -// name = "acctsub-%d" -// resource_group_name = "${azurerm_resource_group.test.name}" -// virtual_network_name = "${azurerm_virtual_network.test.name}" -// address_prefix = "10.0.2.0/24" -//} -// -//resource "azurerm_network_interface" "test" { -// name = "acctni-%d" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// -// ip_configuration { -// name = "testconfiguration1" -// subnet_id = "${azurerm_subnet.test.id}" -// private_ip_address_allocation = "dynamic" -// } -//} -// -//resource "azurerm_storage_account" "test" { -// name = "accsa%d" -// resource_group_name = "${azurerm_resource_group.test.name}" -// location = "westus" -// account_type = "Standard_LRS" -// -// tags { -// environment = "staging" -// } -//} -// -//resource "azurerm_storage_container" "test" { -// name = "vhds" -// resource_group_name = "${azurerm_resource_group.test.name}" -// storage_account_name = "${azurerm_storage_account.test.name}" -// container_access_type = "private" -//} -// -//resource "azurerm_virtual_machine" "test" { -// name = "acctvm-%d" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// network_interface_ids = ["${azurerm_network_interface.test.id}"] -// vm_size = "Standard_A1" -// -// storage_image_reference { -// publisher = "Canonical" -// offer = "UbuntuServer" -// sku = "14.04.2-LTS" -// version = "latest" -// } -// -// storage_os_disk { -// name = "myosdisk1" -// vhd_uri = "${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/myosdisk1.vhd" -// caching = "ReadWrite" -// create_option = "FromImage" -// } -// -// os_profile { -// computer_name = "hostname%d" -// admin_username = "testadmin" -// admin_password = "Password1234!" -// } -// -// os_profile_linux_config { -// disable_password_authentication = false -// } -//} -//` -// -//var testAccAzureRMVirtualMachine_basicWindowsMachine = ` -//resource "azurerm_resource_group" "test" { -// name = "acctestrg-%d" -// location = "West US" -//} -// -//resource "azurerm_virtual_network" "test" { -// name = "acctvn-%d" -// address_space = ["10.0.0.0/16"] -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -//} -// -//resource "azurerm_subnet" "test" { -// name = "acctsub-%d" -// resource_group_name = "${azurerm_resource_group.test.name}" -// virtual_network_name = "${azurerm_virtual_network.test.name}" -// address_prefix = "10.0.2.0/24" -//} -// -//resource "azurerm_network_interface" "test" { -// name = "acctni-%d" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// -// ip_configuration { -// name = "testconfiguration1" -// subnet_id = "${azurerm_subnet.test.id}" -// private_ip_address_allocation = "dynamic" -// } -//} -// -//resource "azurerm_storage_account" "test" { -// name = "accsa%d" -// resource_group_name = "${azurerm_resource_group.test.name}" -// location = "westus" -// account_type = "Standard_LRS" -// -// tags { -// environment = "staging" -// } -//} -// -//resource "azurerm_storage_container" "test" { -// name = "vhds" -// resource_group_name = "${azurerm_resource_group.test.name}" -// storage_account_name = "${azurerm_storage_account.test.name}" -// container_access_type = "private" -//} -// -//resource "azurerm_virtual_machine" "test" { -// name = "acctvm-%d" -// location = "West US" -// resource_group_name = "${azurerm_resource_group.test.name}" -// network_interface_ids = ["${azurerm_network_interface.test.id}"] -// vm_size = "Standard_A0" -// -// storage_image_reference { -// publisher = "MicrosoftWindowsServer" -// offer = "WindowsServer" -// sku = "2012-Datacenter" -// version = "latest" -// } -// -// storage_os_disk { -// name = "myosdisk1" -// vhd_uri = "${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/myosdisk1.vhd" -// caching = "ReadWrite" -// create_option = "FromImage" -// } -// -// os_profile { -// computer_name = "winhost01" -// admin_username = "testadmin" -// admin_password = "Password1234!" -// } -// -// os_profile_windows_config { -// enable_automatic_upgrades = false -// provision_vm_agent = true -// } -//} -//` +import ( + "fmt" + "net/http" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAzureRMVirtualMachine_basicLinuxMachine(t *testing.T) { + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMVirtualMachine_basicLinuxMachine, ri, ri, ri, ri, ri, ri, ri) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMVirtualMachineDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test"), + ), + }, + }, + }) +} + +func TestAccAzureRMVirtualMachine_tags(t *testing.T) { + ri := acctest.RandInt() + preConfig := fmt.Sprintf(testAccAzureRMVirtualMachine_basicLinuxMachine, ri, ri, ri, ri, ri, ri, ri) + postConfig := fmt.Sprintf(testAccAzureRMVirtualMachine_basicLinuxMachineUpdated, ri, ri, ri, ri, ri, ri, ri) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMVirtualMachineDestroy, + Steps: []resource.TestStep{ + { + Config: preConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test"), + resource.TestCheckResourceAttr( + "azurerm_virtual_machine.test", "tags.#", "2"), + resource.TestCheckResourceAttr( + "azurerm_virtual_machine.test", "tags.environment", "Production"), + resource.TestCheckResourceAttr( + "azurerm_virtual_machine.test", "tags.cost-center", "Ops"), + ), + }, + + { + Config: postConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test"), + resource.TestCheckResourceAttr( + "azurerm_virtual_machine.test", "tags.#", "1"), + resource.TestCheckResourceAttr( + "azurerm_virtual_machine.test", "tags.environment", "Production"), + ), + }, + }, + }) +} + +//This is a regression test around https://github.com/hashicorp/terraform/issues/6517 +//Because we use CreateOrUpdate, we were sending an empty password on update requests +func TestAccAzureRMVirtualMachine_updateMachineSize(t *testing.T) { + ri := acctest.RandInt() + preConfig := fmt.Sprintf(testAccAzureRMVirtualMachine_basicLinuxMachine, ri, ri, ri, ri, ri, ri, ri) + postConfig := fmt.Sprintf(testAccAzureRMVirtualMachine_updatedLinuxMachine, ri, ri, ri, ri, ri, ri, ri) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMVirtualMachineDestroy, + Steps: []resource.TestStep{ + { + Config: preConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test"), + resource.TestCheckResourceAttr( + "azurerm_virtual_machine.test", "vm_size", "Standard_A0"), + ), + }, + { + Config: postConfig, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test"), + resource.TestCheckResourceAttr( + "azurerm_virtual_machine.test", "vm_size", "Standard_A1"), + ), + }, + }, + }) +} + +func TestAccAzureRMVirtualMachine_basicWindowsMachine(t *testing.T) { + ri := acctest.RandInt() + config := fmt.Sprintf(testAccAzureRMVirtualMachine_basicWindowsMachine, ri, ri, ri, ri, ri, ri) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMVirtualMachineDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMVirtualMachineExists("azurerm_virtual_machine.test"), + ), + }, + }, + }) +} + +func testCheckAzureRMVirtualMachineExists(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) + } + + vmName := rs.Primary.Attributes["name"] + resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] + if !hasResourceGroup { + return fmt.Errorf("Bad: no resource group found in state for virtual machine: %s", vmName) + } + + conn := testAccProvider.Meta().(*ArmClient).vmClient + + resp, err := conn.Get(resourceGroup, vmName, "") + if err != nil { + return fmt.Errorf("Bad: Get on vmClient: %s", err) + } + + if resp.StatusCode == http.StatusNotFound { + return fmt.Errorf("Bad: VirtualMachine %q (resource group: %q) does not exist", vmName, resourceGroup) + } + + return nil + } +} + +func testCheckAzureRMVirtualMachineDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*ArmClient).vmClient + + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_virtual_machine" { + continue + } + + name := rs.Primary.Attributes["name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] + + resp, err := conn.Get(resourceGroup, name, "") + + if err != nil { + return nil + } + + if resp.StatusCode != http.StatusNotFound { + return fmt.Errorf("Virtual Machine still exists:\n%#v", resp.Properties) + } + } + + return nil +} + +var testAccAzureRMVirtualMachine_basicLinuxMachine = ` +resource "azurerm_resource_group" "test" { + name = "acctestrg-%d" + location = "West US" +} + +resource "azurerm_virtual_network" "test" { + name = "acctvn-%d" + address_space = ["10.0.0.0/16"] + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" +} + +resource "azurerm_subnet" "test" { + name = "acctsub-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + virtual_network_name = "${azurerm_virtual_network.test.name}" + address_prefix = "10.0.2.0/24" +} + +resource "azurerm_network_interface" "test" { + name = "acctni-%d" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + + ip_configuration { + name = "testconfiguration1" + subnet_id = "${azurerm_subnet.test.id}" + private_ip_address_allocation = "dynamic" + } +} + +resource "azurerm_storage_account" "test" { + name = "accsa%d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "westus" + account_type = "Standard_LRS" + + tags { + environment = "staging" + } +} + +resource "azurerm_storage_container" "test" { + name = "vhds" + resource_group_name = "${azurerm_resource_group.test.name}" + storage_account_name = "${azurerm_storage_account.test.name}" + container_access_type = "private" +} + +resource "azurerm_virtual_machine" "test" { + name = "acctvm-%d" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + network_interface_ids = ["${azurerm_network_interface.test.id}"] + vm_size = "Standard_A0" + + storage_image_reference { + publisher = "Canonical" + offer = "UbuntuServer" + sku = "14.04.2-LTS" + version = "latest" + } + + storage_os_disk { + name = "myosdisk1" + vhd_uri = "${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/myosdisk1.vhd" + caching = "ReadWrite" + create_option = "FromImage" + } + + os_profile { + computer_name = "hostname%d" + admin_username = "testadmin" + admin_password = "Password1234!" + } + + os_profile_linux_config { + disable_password_authentication = false + } + + tags { + environment = "Production" + cost-center = "Ops" + } +} +` + +var testAccAzureRMVirtualMachine_basicLinuxMachineUpdated = ` +resource "azurerm_resource_group" "test" { + name = "acctestrg-%d" + location = "West US" +} + +resource "azurerm_virtual_network" "test" { + name = "acctvn-%d" + address_space = ["10.0.0.0/16"] + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" +} + +resource "azurerm_subnet" "test" { + name = "acctsub-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + virtual_network_name = "${azurerm_virtual_network.test.name}" + address_prefix = "10.0.2.0/24" +} + +resource "azurerm_network_interface" "test" { + name = "acctni-%d" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + + ip_configuration { + name = "testconfiguration1" + subnet_id = "${azurerm_subnet.test.id}" + private_ip_address_allocation = "dynamic" + } +} + +resource "azurerm_storage_account" "test" { + name = "accsa%d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "westus" + account_type = "Standard_LRS" + + tags { + environment = "staging" + } +} + +resource "azurerm_storage_container" "test" { + name = "vhds" + resource_group_name = "${azurerm_resource_group.test.name}" + storage_account_name = "${azurerm_storage_account.test.name}" + container_access_type = "private" +} + +resource "azurerm_virtual_machine" "test" { + name = "acctvm-%d" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + network_interface_ids = ["${azurerm_network_interface.test.id}"] + vm_size = "Standard_A0" + + storage_image_reference { + publisher = "Canonical" + offer = "UbuntuServer" + sku = "14.04.2-LTS" + version = "latest" + } + + storage_os_disk { + name = "myosdisk1" + vhd_uri = "${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/myosdisk1.vhd" + caching = "ReadWrite" + create_option = "FromImage" + } + + os_profile { + computer_name = "hostname%d" + admin_username = "testadmin" + admin_password = "Password1234!" + } + + os_profile_linux_config { + disable_password_authentication = false + } + + tags { + environment = "Production" + } +} +` + +var testAccAzureRMVirtualMachine_updatedLinuxMachine = ` +resource "azurerm_resource_group" "test" { + name = "acctestrg-%d" + location = "West US" +} + +resource "azurerm_virtual_network" "test" { + name = "acctvn-%d" + address_space = ["10.0.0.0/16"] + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" +} + +resource "azurerm_subnet" "test" { + name = "acctsub-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + virtual_network_name = "${azurerm_virtual_network.test.name}" + address_prefix = "10.0.2.0/24" +} + +resource "azurerm_network_interface" "test" { + name = "acctni-%d" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + + ip_configuration { + name = "testconfiguration1" + subnet_id = "${azurerm_subnet.test.id}" + private_ip_address_allocation = "dynamic" + } +} + +resource "azurerm_storage_account" "test" { + name = "accsa%d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "westus" + account_type = "Standard_LRS" + + tags { + environment = "staging" + } +} + +resource "azurerm_storage_container" "test" { + name = "vhds" + resource_group_name = "${azurerm_resource_group.test.name}" + storage_account_name = "${azurerm_storage_account.test.name}" + container_access_type = "private" +} + +resource "azurerm_virtual_machine" "test" { + name = "acctvm-%d" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + network_interface_ids = ["${azurerm_network_interface.test.id}"] + vm_size = "Standard_A1" + + storage_image_reference { + publisher = "Canonical" + offer = "UbuntuServer" + sku = "14.04.2-LTS" + version = "latest" + } + + storage_os_disk { + name = "myosdisk1" + vhd_uri = "${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/myosdisk1.vhd" + caching = "ReadWrite" + create_option = "FromImage" + } + + os_profile { + computer_name = "hostname%d" + admin_username = "testadmin" + admin_password = "Password1234!" + } + + os_profile_linux_config { + disable_password_authentication = false + } +} +` + +var testAccAzureRMVirtualMachine_basicWindowsMachine = ` +resource "azurerm_resource_group" "test" { + name = "acctestrg-%d" + location = "West US" +} + +resource "azurerm_virtual_network" "test" { + name = "acctvn-%d" + address_space = ["10.0.0.0/16"] + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" +} + +resource "azurerm_subnet" "test" { + name = "acctsub-%d" + resource_group_name = "${azurerm_resource_group.test.name}" + virtual_network_name = "${azurerm_virtual_network.test.name}" + address_prefix = "10.0.2.0/24" +} + +resource "azurerm_network_interface" "test" { + name = "acctni-%d" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + + ip_configuration { + name = "testconfiguration1" + subnet_id = "${azurerm_subnet.test.id}" + private_ip_address_allocation = "dynamic" + } +} + +resource "azurerm_storage_account" "test" { + name = "accsa%d" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "westus" + account_type = "Standard_LRS" + + tags { + environment = "staging" + } +} + +resource "azurerm_storage_container" "test" { + name = "vhds" + resource_group_name = "${azurerm_resource_group.test.name}" + storage_account_name = "${azurerm_storage_account.test.name}" + container_access_type = "private" +} + +resource "azurerm_virtual_machine" "test" { + name = "acctvm-%d" + location = "West US" + resource_group_name = "${azurerm_resource_group.test.name}" + network_interface_ids = ["${azurerm_network_interface.test.id}"] + vm_size = "Standard_A0" + + storage_image_reference { + publisher = "MicrosoftWindowsServer" + offer = "WindowsServer" + sku = "2012-Datacenter" + version = "latest" + } + + storage_os_disk { + name = "myosdisk1" + vhd_uri = "${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/myosdisk1.vhd" + caching = "ReadWrite" + create_option = "FromImage" + } + + os_profile { + computer_name = "winhost01" + admin_username = "testadmin" + admin_password = "Password1234!" + } + + os_profile_windows_config { + enable_automatic_upgrades = false + provision_vm_agent = true + } +} +` From 578c37877ec9ab1cd75428c1b6b70dd0960dba3b Mon Sep 17 00:00:00 2001 From: James Nugent Date: Wed, 1 Jun 2016 20:01:31 -0500 Subject: [PATCH 17/17] provider/azure: Fix management client upgrade --- .../azure/resource_azure_storage_blob.go | 2 +- .../golang.org/x/crypto/pkcs12/bmp-string.go | 50 +++ vendor/golang.org/x/crypto/pkcs12/crypto.go | 131 +++++++ vendor/golang.org/x/crypto/pkcs12/errors.go | 23 ++ .../x/crypto/pkcs12/internal/rc2/rc2.go | 274 ++++++++++++++ vendor/golang.org/x/crypto/pkcs12/mac.go | 45 +++ vendor/golang.org/x/crypto/pkcs12/pbkdf.go | 170 +++++++++ vendor/golang.org/x/crypto/pkcs12/pkcs12.go | 342 ++++++++++++++++++ vendor/golang.org/x/crypto/pkcs12/safebags.go | 57 +++ 9 files changed, 1093 insertions(+), 1 deletion(-) create mode 100644 vendor/golang.org/x/crypto/pkcs12/bmp-string.go create mode 100644 vendor/golang.org/x/crypto/pkcs12/crypto.go create mode 100644 vendor/golang.org/x/crypto/pkcs12/errors.go create mode 100644 vendor/golang.org/x/crypto/pkcs12/internal/rc2/rc2.go create mode 100644 vendor/golang.org/x/crypto/pkcs12/mac.go create mode 100644 vendor/golang.org/x/crypto/pkcs12/pbkdf.go create mode 100644 vendor/golang.org/x/crypto/pkcs12/pkcs12.go create mode 100644 vendor/golang.org/x/crypto/pkcs12/safebags.go diff --git a/builtin/providers/azure/resource_azure_storage_blob.go b/builtin/providers/azure/resource_azure_storage_blob.go index 449c24ae5bb6..272874bf927a 100644 --- a/builtin/providers/azure/resource_azure_storage_blob.go +++ b/builtin/providers/azure/resource_azure_storage_blob.go @@ -163,7 +163,7 @@ func resourceAzureStorageBlobDelete(d *schema.ResourceData, meta interface{}) er log.Println("[INFO] Issuing storage blob delete command off Azure.") name := d.Get("name").(string) cont := d.Get("storage_container_name").(string) - if _, err = blobClient.DeleteBlobIfExists(cont, name); err != nil { + if _, err = blobClient.DeleteBlobIfExists(cont, name, make(map[string]string)); err != nil { return fmt.Errorf("Error whilst deleting storage blob: %s", err) } diff --git a/vendor/golang.org/x/crypto/pkcs12/bmp-string.go b/vendor/golang.org/x/crypto/pkcs12/bmp-string.go new file mode 100644 index 000000000000..284d2a68f1ee --- /dev/null +++ b/vendor/golang.org/x/crypto/pkcs12/bmp-string.go @@ -0,0 +1,50 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package pkcs12 + +import ( + "errors" + "unicode/utf16" +) + +// bmpString returns s encoded in UCS-2 with a zero terminator. +func bmpString(s string) ([]byte, error) { + // References: + // https://tools.ietf.org/html/rfc7292#appendix-B.1 + // http://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane + // - non-BMP characters are encoded in UTF 16 by using a surrogate pair of 16-bit codes + // EncodeRune returns 0xfffd if the rune does not need special encoding + // - the above RFC provides the info that BMPStrings are NULL terminated. + + ret := make([]byte, 0, 2*len(s)+2) + + for _, r := range s { + if t, _ := utf16.EncodeRune(r); t != 0xfffd { + return nil, errors.New("pkcs12: string contains characters that cannot be encoded in UCS-2") + } + ret = append(ret, byte(r/256), byte(r%256)) + } + + return append(ret, 0, 0), nil +} + +func decodeBMPString(bmpString []byte) (string, error) { + if len(bmpString)%2 != 0 { + return "", errors.New("pkcs12: odd-length BMP string") + } + + // strip terminator if present + if l := len(bmpString); l >= 2 && bmpString[l-1] == 0 && bmpString[l-2] == 0 { + bmpString = bmpString[:l-2] + } + + s := make([]uint16, 0, len(bmpString)/2) + for len(bmpString) > 0 { + s = append(s, uint16(bmpString[0])<<8+uint16(bmpString[1])) + bmpString = bmpString[2:] + } + + return string(utf16.Decode(s)), nil +} diff --git a/vendor/golang.org/x/crypto/pkcs12/crypto.go b/vendor/golang.org/x/crypto/pkcs12/crypto.go new file mode 100644 index 000000000000..4bd4470ec041 --- /dev/null +++ b/vendor/golang.org/x/crypto/pkcs12/crypto.go @@ -0,0 +1,131 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package pkcs12 + +import ( + "bytes" + "crypto/cipher" + "crypto/des" + "crypto/x509/pkix" + "encoding/asn1" + "errors" + + "golang.org/x/crypto/pkcs12/internal/rc2" +) + +var ( + oidPBEWithSHAAnd3KeyTripleDESCBC = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 1, 3}) + oidPBEWithSHAAnd40BitRC2CBC = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 1, 6}) +) + +// pbeCipher is an abstraction of a PKCS#12 cipher. +type pbeCipher interface { + // create returns a cipher.Block given a key. + create(key []byte) (cipher.Block, error) + // deriveKey returns a key derived from the given password and salt. + deriveKey(salt, password []byte, iterations int) []byte + // deriveKey returns an IV derived from the given password and salt. + deriveIV(salt, password []byte, iterations int) []byte +} + +type shaWithTripleDESCBC struct{} + +func (shaWithTripleDESCBC) create(key []byte) (cipher.Block, error) { + return des.NewTripleDESCipher(key) +} + +func (shaWithTripleDESCBC) deriveKey(salt, password []byte, iterations int) []byte { + return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 1, 24) +} + +func (shaWithTripleDESCBC) deriveIV(salt, password []byte, iterations int) []byte { + return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 2, 8) +} + +type shaWith40BitRC2CBC struct{} + +func (shaWith40BitRC2CBC) create(key []byte) (cipher.Block, error) { + return rc2.New(key, len(key)*8) +} + +func (shaWith40BitRC2CBC) deriveKey(salt, password []byte, iterations int) []byte { + return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 1, 5) +} + +func (shaWith40BitRC2CBC) deriveIV(salt, password []byte, iterations int) []byte { + return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 2, 8) +} + +type pbeParams struct { + Salt []byte + Iterations int +} + +func pbDecrypterFor(algorithm pkix.AlgorithmIdentifier, password []byte) (cipher.BlockMode, int, error) { + var cipherType pbeCipher + + switch { + case algorithm.Algorithm.Equal(oidPBEWithSHAAnd3KeyTripleDESCBC): + cipherType = shaWithTripleDESCBC{} + case algorithm.Algorithm.Equal(oidPBEWithSHAAnd40BitRC2CBC): + cipherType = shaWith40BitRC2CBC{} + default: + return nil, 0, NotImplementedError("algorithm " + algorithm.Algorithm.String() + " is not supported") + } + + var params pbeParams + if err := unmarshal(algorithm.Parameters.FullBytes, ¶ms); err != nil { + return nil, 0, err + } + + key := cipherType.deriveKey(params.Salt, password, params.Iterations) + iv := cipherType.deriveIV(params.Salt, password, params.Iterations) + + block, err := cipherType.create(key) + if err != nil { + return nil, 0, err + } + + return cipher.NewCBCDecrypter(block, iv), block.BlockSize(), nil +} + +func pbDecrypt(info decryptable, password []byte) (decrypted []byte, err error) { + cbc, blockSize, err := pbDecrypterFor(info.Algorithm(), password) + if err != nil { + return nil, err + } + + encrypted := info.Data() + if len(encrypted) == 0 { + return nil, errors.New("pkcs12: empty encrypted data") + } + if len(encrypted)%blockSize != 0 { + return nil, errors.New("pkcs12: input is not a multiple of the block size") + } + decrypted = make([]byte, len(encrypted)) + cbc.CryptBlocks(decrypted, encrypted) + + psLen := int(decrypted[len(decrypted)-1]) + if psLen == 0 || psLen > blockSize { + return nil, ErrDecryption + } + + if len(decrypted) < psLen { + return nil, ErrDecryption + } + ps := decrypted[len(decrypted)-psLen:] + decrypted = decrypted[:len(decrypted)-psLen] + if bytes.Compare(ps, bytes.Repeat([]byte{byte(psLen)}, psLen)) != 0 { + return nil, ErrDecryption + } + + return +} + +// decryptable abstracts a object that contains ciphertext. +type decryptable interface { + Algorithm() pkix.AlgorithmIdentifier + Data() []byte +} diff --git a/vendor/golang.org/x/crypto/pkcs12/errors.go b/vendor/golang.org/x/crypto/pkcs12/errors.go new file mode 100644 index 000000000000..7377ce6fb2b8 --- /dev/null +++ b/vendor/golang.org/x/crypto/pkcs12/errors.go @@ -0,0 +1,23 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package pkcs12 + +import "errors" + +var ( + // ErrDecryption represents a failure to decrypt the input. + ErrDecryption = errors.New("pkcs12: decryption error, incorrect padding") + + // ErrIncorrectPassword is returned when an incorrect password is detected. + // Usually, P12/PFX data is signed to be able to verify the password. + ErrIncorrectPassword = errors.New("pkcs12: decryption password incorrect") +) + +// NotImplementedError indicates that the input is not currently supported. +type NotImplementedError string + +func (e NotImplementedError) Error() string { + return "pkcs12: " + string(e) +} diff --git a/vendor/golang.org/x/crypto/pkcs12/internal/rc2/rc2.go b/vendor/golang.org/x/crypto/pkcs12/internal/rc2/rc2.go new file mode 100644 index 000000000000..8c7090258c5a --- /dev/null +++ b/vendor/golang.org/x/crypto/pkcs12/internal/rc2/rc2.go @@ -0,0 +1,274 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package rc2 implements the RC2 cipher +/* +https://www.ietf.org/rfc/rfc2268.txt +http://people.csail.mit.edu/rivest/pubs/KRRR98.pdf + +This code is licensed under the MIT license. +*/ +package rc2 + +import ( + "crypto/cipher" + "encoding/binary" +) + +// The rc2 block size in bytes +const BlockSize = 8 + +type rc2Cipher struct { + k [64]uint16 +} + +// New returns a new rc2 cipher with the given key and effective key length t1 +func New(key []byte, t1 int) (cipher.Block, error) { + // TODO(dgryski): error checking for key length + return &rc2Cipher{ + k: expandKey(key, t1), + }, nil +} + +func (*rc2Cipher) BlockSize() int { return BlockSize } + +var piTable = [256]byte{ + 0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d, + 0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e, 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2, + 0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13, 0x61, 0x45, 0x6d, 0x8d, 0x09, 0x81, 0x7d, 0x32, + 0xbd, 0x8f, 0x40, 0xeb, 0x86, 0xb7, 0x7b, 0x0b, 0xf0, 0x95, 0x21, 0x22, 0x5c, 0x6b, 0x4e, 0x82, + 0x54, 0xd6, 0x65, 0x93, 0xce, 0x60, 0xb2, 0x1c, 0x73, 0x56, 0xc0, 0x14, 0xa7, 0x8c, 0xf1, 0xdc, + 0x12, 0x75, 0xca, 0x1f, 0x3b, 0xbe, 0xe4, 0xd1, 0x42, 0x3d, 0xd4, 0x30, 0xa3, 0x3c, 0xb6, 0x26, + 0x6f, 0xbf, 0x0e, 0xda, 0x46, 0x69, 0x07, 0x57, 0x27, 0xf2, 0x1d, 0x9b, 0xbc, 0x94, 0x43, 0x03, + 0xf8, 0x11, 0xc7, 0xf6, 0x90, 0xef, 0x3e, 0xe7, 0x06, 0xc3, 0xd5, 0x2f, 0xc8, 0x66, 0x1e, 0xd7, + 0x08, 0xe8, 0xea, 0xde, 0x80, 0x52, 0xee, 0xf7, 0x84, 0xaa, 0x72, 0xac, 0x35, 0x4d, 0x6a, 0x2a, + 0x96, 0x1a, 0xd2, 0x71, 0x5a, 0x15, 0x49, 0x74, 0x4b, 0x9f, 0xd0, 0x5e, 0x04, 0x18, 0xa4, 0xec, + 0xc2, 0xe0, 0x41, 0x6e, 0x0f, 0x51, 0xcb, 0xcc, 0x24, 0x91, 0xaf, 0x50, 0xa1, 0xf4, 0x70, 0x39, + 0x99, 0x7c, 0x3a, 0x85, 0x23, 0xb8, 0xb4, 0x7a, 0xfc, 0x02, 0x36, 0x5b, 0x25, 0x55, 0x97, 0x31, + 0x2d, 0x5d, 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae, 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9, + 0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c, 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9, + 0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e, + 0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad, +} + +func expandKey(key []byte, t1 int) [64]uint16 { + + l := make([]byte, 128) + copy(l, key) + + var t = len(key) + var t8 = (t1 + 7) / 8 + var tm = byte(255 % uint(1<<(8+uint(t1)-8*uint(t8)))) + + for i := len(key); i < 128; i++ { + l[i] = piTable[l[i-1]+l[uint8(i-t)]] + } + + l[128-t8] = piTable[l[128-t8]&tm] + + for i := 127 - t8; i >= 0; i-- { + l[i] = piTable[l[i+1]^l[i+t8]] + } + + var k [64]uint16 + + for i := range k { + k[i] = uint16(l[2*i]) + uint16(l[2*i+1])*256 + } + + return k +} + +func rotl16(x uint16, b uint) uint16 { + return (x >> (16 - b)) | (x << b) +} + +func (c *rc2Cipher) Encrypt(dst, src []byte) { + + r0 := binary.LittleEndian.Uint16(src[0:]) + r1 := binary.LittleEndian.Uint16(src[2:]) + r2 := binary.LittleEndian.Uint16(src[4:]) + r3 := binary.LittleEndian.Uint16(src[6:]) + + var j int + + for j <= 16 { + // mix r0 + r0 = r0 + c.k[j] + (r3 & r2) + ((^r3) & r1) + r0 = rotl16(r0, 1) + j++ + + // mix r1 + r1 = r1 + c.k[j] + (r0 & r3) + ((^r0) & r2) + r1 = rotl16(r1, 2) + j++ + + // mix r2 + r2 = r2 + c.k[j] + (r1 & r0) + ((^r1) & r3) + r2 = rotl16(r2, 3) + j++ + + // mix r3 + r3 = r3 + c.k[j] + (r2 & r1) + ((^r2) & r0) + r3 = rotl16(r3, 5) + j++ + + } + + r0 = r0 + c.k[r3&63] + r1 = r1 + c.k[r0&63] + r2 = r2 + c.k[r1&63] + r3 = r3 + c.k[r2&63] + + for j <= 40 { + + // mix r0 + r0 = r0 + c.k[j] + (r3 & r2) + ((^r3) & r1) + r0 = rotl16(r0, 1) + j++ + + // mix r1 + r1 = r1 + c.k[j] + (r0 & r3) + ((^r0) & r2) + r1 = rotl16(r1, 2) + j++ + + // mix r2 + r2 = r2 + c.k[j] + (r1 & r0) + ((^r1) & r3) + r2 = rotl16(r2, 3) + j++ + + // mix r3 + r3 = r3 + c.k[j] + (r2 & r1) + ((^r2) & r0) + r3 = rotl16(r3, 5) + j++ + + } + + r0 = r0 + c.k[r3&63] + r1 = r1 + c.k[r0&63] + r2 = r2 + c.k[r1&63] + r3 = r3 + c.k[r2&63] + + for j <= 60 { + + // mix r0 + r0 = r0 + c.k[j] + (r3 & r2) + ((^r3) & r1) + r0 = rotl16(r0, 1) + j++ + + // mix r1 + r1 = r1 + c.k[j] + (r0 & r3) + ((^r0) & r2) + r1 = rotl16(r1, 2) + j++ + + // mix r2 + r2 = r2 + c.k[j] + (r1 & r0) + ((^r1) & r3) + r2 = rotl16(r2, 3) + j++ + + // mix r3 + r3 = r3 + c.k[j] + (r2 & r1) + ((^r2) & r0) + r3 = rotl16(r3, 5) + j++ + } + + binary.LittleEndian.PutUint16(dst[0:], r0) + binary.LittleEndian.PutUint16(dst[2:], r1) + binary.LittleEndian.PutUint16(dst[4:], r2) + binary.LittleEndian.PutUint16(dst[6:], r3) +} + +func (c *rc2Cipher) Decrypt(dst, src []byte) { + + r0 := binary.LittleEndian.Uint16(src[0:]) + r1 := binary.LittleEndian.Uint16(src[2:]) + r2 := binary.LittleEndian.Uint16(src[4:]) + r3 := binary.LittleEndian.Uint16(src[6:]) + + j := 63 + + for j >= 44 { + // unmix r3 + r3 = rotl16(r3, 16-5) + r3 = r3 - c.k[j] - (r2 & r1) - ((^r2) & r0) + j-- + + // unmix r2 + r2 = rotl16(r2, 16-3) + r2 = r2 - c.k[j] - (r1 & r0) - ((^r1) & r3) + j-- + + // unmix r1 + r1 = rotl16(r1, 16-2) + r1 = r1 - c.k[j] - (r0 & r3) - ((^r0) & r2) + j-- + + // unmix r0 + r0 = rotl16(r0, 16-1) + r0 = r0 - c.k[j] - (r3 & r2) - ((^r3) & r1) + j-- + } + + r3 = r3 - c.k[r2&63] + r2 = r2 - c.k[r1&63] + r1 = r1 - c.k[r0&63] + r0 = r0 - c.k[r3&63] + + for j >= 20 { + // unmix r3 + r3 = rotl16(r3, 16-5) + r3 = r3 - c.k[j] - (r2 & r1) - ((^r2) & r0) + j-- + + // unmix r2 + r2 = rotl16(r2, 16-3) + r2 = r2 - c.k[j] - (r1 & r0) - ((^r1) & r3) + j-- + + // unmix r1 + r1 = rotl16(r1, 16-2) + r1 = r1 - c.k[j] - (r0 & r3) - ((^r0) & r2) + j-- + + // unmix r0 + r0 = rotl16(r0, 16-1) + r0 = r0 - c.k[j] - (r3 & r2) - ((^r3) & r1) + j-- + + } + + r3 = r3 - c.k[r2&63] + r2 = r2 - c.k[r1&63] + r1 = r1 - c.k[r0&63] + r0 = r0 - c.k[r3&63] + + for j >= 0 { + + // unmix r3 + r3 = rotl16(r3, 16-5) + r3 = r3 - c.k[j] - (r2 & r1) - ((^r2) & r0) + j-- + + // unmix r2 + r2 = rotl16(r2, 16-3) + r2 = r2 - c.k[j] - (r1 & r0) - ((^r1) & r3) + j-- + + // unmix r1 + r1 = rotl16(r1, 16-2) + r1 = r1 - c.k[j] - (r0 & r3) - ((^r0) & r2) + j-- + + // unmix r0 + r0 = rotl16(r0, 16-1) + r0 = r0 - c.k[j] - (r3 & r2) - ((^r3) & r1) + j-- + + } + + binary.LittleEndian.PutUint16(dst[0:], r0) + binary.LittleEndian.PutUint16(dst[2:], r1) + binary.LittleEndian.PutUint16(dst[4:], r2) + binary.LittleEndian.PutUint16(dst[6:], r3) +} diff --git a/vendor/golang.org/x/crypto/pkcs12/mac.go b/vendor/golang.org/x/crypto/pkcs12/mac.go new file mode 100644 index 000000000000..5f38aa7de83c --- /dev/null +++ b/vendor/golang.org/x/crypto/pkcs12/mac.go @@ -0,0 +1,45 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package pkcs12 + +import ( + "crypto/hmac" + "crypto/sha1" + "crypto/x509/pkix" + "encoding/asn1" +) + +type macData struct { + Mac digestInfo + MacSalt []byte + Iterations int `asn1:"optional,default:1"` +} + +// from PKCS#7: +type digestInfo struct { + Algorithm pkix.AlgorithmIdentifier + Digest []byte +} + +var ( + oidSHA1 = asn1.ObjectIdentifier([]int{1, 3, 14, 3, 2, 26}) +) + +func verifyMac(macData *macData, message, password []byte) error { + if !macData.Mac.Algorithm.Algorithm.Equal(oidSHA1) { + return NotImplementedError("unknown digest algorithm: " + macData.Mac.Algorithm.Algorithm.String()) + } + + key := pbkdf(sha1Sum, 20, 64, macData.MacSalt, password, macData.Iterations, 3, 20) + + mac := hmac.New(sha1.New, key) + mac.Write(message) + expectedMAC := mac.Sum(nil) + + if !hmac.Equal(macData.Mac.Digest, expectedMAC) { + return ErrIncorrectPassword + } + return nil +} diff --git a/vendor/golang.org/x/crypto/pkcs12/pbkdf.go b/vendor/golang.org/x/crypto/pkcs12/pbkdf.go new file mode 100644 index 000000000000..5c419d41e32c --- /dev/null +++ b/vendor/golang.org/x/crypto/pkcs12/pbkdf.go @@ -0,0 +1,170 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package pkcs12 + +import ( + "bytes" + "crypto/sha1" + "math/big" +) + +var ( + one = big.NewInt(1) +) + +// sha1Sum returns the SHA-1 hash of in. +func sha1Sum(in []byte) []byte { + sum := sha1.Sum(in) + return sum[:] +} + +// fillWithRepeats returns v*ceiling(len(pattern) / v) bytes consisting of +// repeats of pattern. +func fillWithRepeats(pattern []byte, v int) []byte { + if len(pattern) == 0 { + return nil + } + outputLen := v * ((len(pattern) + v - 1) / v) + return bytes.Repeat(pattern, (outputLen+len(pattern)-1)/len(pattern))[:outputLen] +} + +func pbkdf(hash func([]byte) []byte, u, v int, salt, password []byte, r int, ID byte, size int) (key []byte) { + // implementation of https://tools.ietf.org/html/rfc7292#appendix-B.2 , RFC text verbatim in comments + + // Let H be a hash function built around a compression function f: + + // Z_2^u x Z_2^v -> Z_2^u + + // (that is, H has a chaining variable and output of length u bits, and + // the message input to the compression function of H is v bits). The + // values for u and v are as follows: + + // HASH FUNCTION VALUE u VALUE v + // MD2, MD5 128 512 + // SHA-1 160 512 + // SHA-224 224 512 + // SHA-256 256 512 + // SHA-384 384 1024 + // SHA-512 512 1024 + // SHA-512/224 224 1024 + // SHA-512/256 256 1024 + + // Furthermore, let r be the iteration count. + + // We assume here that u and v are both multiples of 8, as are the + // lengths of the password and salt strings (which we denote by p and s, + // respectively) and the number n of pseudorandom bits required. In + // addition, u and v are of course non-zero. + + // For information on security considerations for MD5 [19], see [25] and + // [1], and on those for MD2, see [18]. + + // The following procedure can be used to produce pseudorandom bits for + // a particular "purpose" that is identified by a byte called "ID". + // This standard specifies 3 different values for the ID byte: + + // 1. If ID=1, then the pseudorandom bits being produced are to be used + // as key material for performing encryption or decryption. + + // 2. If ID=2, then the pseudorandom bits being produced are to be used + // as an IV (Initial Value) for encryption or decryption. + + // 3. If ID=3, then the pseudorandom bits being produced are to be used + // as an integrity key for MACing. + + // 1. Construct a string, D (the "diversifier"), by concatenating v/8 + // copies of ID. + var D []byte + for i := 0; i < v; i++ { + D = append(D, ID) + } + + // 2. Concatenate copies of the salt together to create a string S of + // length v(ceiling(s/v)) bits (the final copy of the salt may be + // truncated to create S). Note that if the salt is the empty + // string, then so is S. + + S := fillWithRepeats(salt, v) + + // 3. Concatenate copies of the password together to create a string P + // of length v(ceiling(p/v)) bits (the final copy of the password + // may be truncated to create P). Note that if the password is the + // empty string, then so is P. + + P := fillWithRepeats(password, v) + + // 4. Set I=S||P to be the concatenation of S and P. + I := append(S, P...) + + // 5. Set c=ceiling(n/u). + c := (size + u - 1) / u + + // 6. For i=1, 2, ..., c, do the following: + A := make([]byte, c*20) + var IjBuf []byte + for i := 0; i < c; i++ { + // A. Set A2=H^r(D||I). (i.e., the r-th hash of D||1, + // H(H(H(... H(D||I)))) + Ai := hash(append(D, I...)) + for j := 1; j < r; j++ { + Ai = hash(Ai) + } + copy(A[i*20:], Ai[:]) + + if i < c-1 { // skip on last iteration + // B. Concatenate copies of Ai to create a string B of length v + // bits (the final copy of Ai may be truncated to create B). + var B []byte + for len(B) < v { + B = append(B, Ai[:]...) + } + B = B[:v] + + // C. Treating I as a concatenation I_0, I_1, ..., I_(k-1) of v-bit + // blocks, where k=ceiling(s/v)+ceiling(p/v), modify I by + // setting I_j=(I_j+B+1) mod 2^v for each j. + { + Bbi := new(big.Int).SetBytes(B) + Ij := new(big.Int) + + for j := 0; j < len(I)/v; j++ { + Ij.SetBytes(I[j*v : (j+1)*v]) + Ij.Add(Ij, Bbi) + Ij.Add(Ij, one) + Ijb := Ij.Bytes() + // We expect Ijb to be exactly v bytes, + // if it is longer or shorter we must + // adjust it accordingly. + if len(Ijb) > v { + Ijb = Ijb[len(Ijb)-v:] + } + if len(Ijb) < v { + if IjBuf == nil { + IjBuf = make([]byte, v) + } + bytesShort := v - len(Ijb) + for i := 0; i < bytesShort; i++ { + IjBuf[i] = 0 + } + copy(IjBuf[bytesShort:], Ijb) + Ijb = IjBuf + } + copy(I[j*v:(j+1)*v], Ijb) + } + } + } + } + // 7. Concatenate A_1, A_2, ..., A_c together to form a pseudorandom + // bit string, A. + + // 8. Use the first n bits of A as the output of this entire process. + return A[:size] + + // If the above process is being used to generate a DES key, the process + // should be used to create 64 random bits, and the key's parity bits + // should be set after the 64 bits have been produced. Similar concerns + // hold for 2-key and 3-key triple-DES keys, for CDMF keys, and for any + // similar keys with parity bits "built into them". +} diff --git a/vendor/golang.org/x/crypto/pkcs12/pkcs12.go b/vendor/golang.org/x/crypto/pkcs12/pkcs12.go new file mode 100644 index 000000000000..ad6341e60fa4 --- /dev/null +++ b/vendor/golang.org/x/crypto/pkcs12/pkcs12.go @@ -0,0 +1,342 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package pkcs12 implements some of PKCS#12. +// +// This implementation is distilled from https://tools.ietf.org/html/rfc7292 +// and referenced documents. It is intended for decoding P12/PFX-stored +// certificates and keys for use with the crypto/tls package. +package pkcs12 + +import ( + "crypto/ecdsa" + "crypto/rsa" + "crypto/x509" + "crypto/x509/pkix" + "encoding/asn1" + "encoding/hex" + "encoding/pem" + "errors" +) + +var ( + oidDataContentType = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 7, 1}) + oidEncryptedDataContentType = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 7, 6}) + + oidFriendlyName = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 9, 20}) + oidLocalKeyID = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 9, 21}) + oidMicrosoftCSPName = asn1.ObjectIdentifier([]int{1, 3, 6, 1, 4, 1, 311, 17, 1}) +) + +type pfxPdu struct { + Version int + AuthSafe contentInfo + MacData macData `asn1:"optional"` +} + +type contentInfo struct { + ContentType asn1.ObjectIdentifier + Content asn1.RawValue `asn1:"tag:0,explicit,optional"` +} + +type encryptedData struct { + Version int + EncryptedContentInfo encryptedContentInfo +} + +type encryptedContentInfo struct { + ContentType asn1.ObjectIdentifier + ContentEncryptionAlgorithm pkix.AlgorithmIdentifier + EncryptedContent []byte `asn1:"tag:0,optional"` +} + +func (i encryptedContentInfo) Algorithm() pkix.AlgorithmIdentifier { + return i.ContentEncryptionAlgorithm +} + +func (i encryptedContentInfo) Data() []byte { return i.EncryptedContent } + +type safeBag struct { + Id asn1.ObjectIdentifier + Value asn1.RawValue `asn1:"tag:0,explicit"` + Attributes []pkcs12Attribute `asn1:"set,optional"` +} + +type pkcs12Attribute struct { + Id asn1.ObjectIdentifier + Value asn1.RawValue `asn1:"set"` +} + +type encryptedPrivateKeyInfo struct { + AlgorithmIdentifier pkix.AlgorithmIdentifier + EncryptedData []byte +} + +func (i encryptedPrivateKeyInfo) Algorithm() pkix.AlgorithmIdentifier { + return i.AlgorithmIdentifier +} + +func (i encryptedPrivateKeyInfo) Data() []byte { + return i.EncryptedData +} + +// PEM block types +const ( + certificateType = "CERTIFICATE" + privateKeyType = "PRIVATE KEY" +) + +// unmarshal calls asn1.Unmarshal, but also returns an error if there is any +// trailing data after unmarshaling. +func unmarshal(in []byte, out interface{}) error { + trailing, err := asn1.Unmarshal(in, out) + if err != nil { + return err + } + if len(trailing) != 0 { + return errors.New("pkcs12: trailing data found") + } + return nil +} + +// ConvertToPEM converts all "safe bags" contained in pfxData to PEM blocks. +func ToPEM(pfxData []byte, password string) ([]*pem.Block, error) { + encodedPassword, err := bmpString(password) + if err != nil { + return nil, ErrIncorrectPassword + } + + bags, encodedPassword, err := getSafeContents(pfxData, encodedPassword) + + blocks := make([]*pem.Block, 0, len(bags)) + for _, bag := range bags { + block, err := convertBag(&bag, encodedPassword) + if err != nil { + return nil, err + } + blocks = append(blocks, block) + } + + return blocks, nil +} + +func convertBag(bag *safeBag, password []byte) (*pem.Block, error) { + block := &pem.Block{ + Headers: make(map[string]string), + } + + for _, attribute := range bag.Attributes { + k, v, err := convertAttribute(&attribute) + if err != nil { + return nil, err + } + block.Headers[k] = v + } + + switch { + case bag.Id.Equal(oidCertBag): + block.Type = certificateType + certsData, err := decodeCertBag(bag.Value.Bytes) + if err != nil { + return nil, err + } + block.Bytes = certsData + case bag.Id.Equal(oidPKCS8ShroundedKeyBag): + block.Type = privateKeyType + + key, err := decodePkcs8ShroudedKeyBag(bag.Value.Bytes, password) + if err != nil { + return nil, err + } + + switch key := key.(type) { + case *rsa.PrivateKey: + block.Bytes = x509.MarshalPKCS1PrivateKey(key) + case *ecdsa.PrivateKey: + block.Bytes, err = x509.MarshalECPrivateKey(key) + if err != nil { + return nil, err + } + default: + return nil, errors.New("found unknown private key type in PKCS#8 wrapping") + } + default: + return nil, errors.New("don't know how to convert a safe bag of type " + bag.Id.String()) + } + return block, nil +} + +func convertAttribute(attribute *pkcs12Attribute) (key, value string, err error) { + isString := false + + switch { + case attribute.Id.Equal(oidFriendlyName): + key = "friendlyName" + isString = true + case attribute.Id.Equal(oidLocalKeyID): + key = "localKeyId" + case attribute.Id.Equal(oidMicrosoftCSPName): + // This key is chosen to match OpenSSL. + key = "Microsoft CSP Name" + isString = true + default: + return "", "", errors.New("pkcs12: unknown attribute with OID " + attribute.Id.String()) + } + + if isString { + if err := unmarshal(attribute.Value.Bytes, &attribute.Value); err != nil { + return "", "", err + } + if value, err = decodeBMPString(attribute.Value.Bytes); err != nil { + return "", "", err + } + } else { + var id []byte + if err := unmarshal(attribute.Value.Bytes, &id); err != nil { + return "", "", err + } + value = hex.EncodeToString(id) + } + + return key, value, nil +} + +// Decode extracts a certificate and private key from pfxData. This function +// assumes that there is only one certificate and only one private key in the +// pfxData. +func Decode(pfxData []byte, password string) (privateKey interface{}, certificate *x509.Certificate, err error) { + encodedPassword, err := bmpString(password) + if err != nil { + return nil, nil, err + } + + bags, encodedPassword, err := getSafeContents(pfxData, encodedPassword) + if err != nil { + return nil, nil, err + } + + if len(bags) != 2 { + err = errors.New("pkcs12: expected exactly two safe bags in the PFX PDU") + return + } + + for _, bag := range bags { + switch { + case bag.Id.Equal(oidCertBag): + if certificate != nil { + err = errors.New("pkcs12: expected exactly one certificate bag") + } + + certsData, err := decodeCertBag(bag.Value.Bytes) + if err != nil { + return nil, nil, err + } + certs, err := x509.ParseCertificates(certsData) + if err != nil { + return nil, nil, err + } + if len(certs) != 1 { + err = errors.New("pkcs12: expected exactly one certificate in the certBag") + return nil, nil, err + } + certificate = certs[0] + + case bag.Id.Equal(oidPKCS8ShroundedKeyBag): + if privateKey != nil { + err = errors.New("pkcs12: expected exactly one key bag") + } + + if privateKey, err = decodePkcs8ShroudedKeyBag(bag.Value.Bytes, encodedPassword); err != nil { + return nil, nil, err + } + } + } + + if certificate == nil { + return nil, nil, errors.New("pkcs12: certificate missing") + } + if privateKey == nil { + return nil, nil, errors.New("pkcs12: private key missing") + } + + return +} + +func getSafeContents(p12Data, password []byte) (bags []safeBag, updatedPassword []byte, err error) { + pfx := new(pfxPdu) + if err := unmarshal(p12Data, pfx); err != nil { + return nil, nil, errors.New("pkcs12: error reading P12 data: " + err.Error()) + } + + if pfx.Version != 3 { + return nil, nil, NotImplementedError("can only decode v3 PFX PDU's") + } + + if !pfx.AuthSafe.ContentType.Equal(oidDataContentType) { + return nil, nil, NotImplementedError("only password-protected PFX is implemented") + } + + // unmarshal the explicit bytes in the content for type 'data' + if err := unmarshal(pfx.AuthSafe.Content.Bytes, &pfx.AuthSafe.Content); err != nil { + return nil, nil, err + } + + if len(pfx.MacData.Mac.Algorithm.Algorithm) == 0 { + return nil, nil, errors.New("pkcs12: no MAC in data") + } + + if err := verifyMac(&pfx.MacData, pfx.AuthSafe.Content.Bytes, password); err != nil { + if err == ErrIncorrectPassword && len(password) == 2 && password[0] == 0 && password[1] == 0 { + // some implementations use an empty byte array + // for the empty string password try one more + // time with empty-empty password + password = nil + err = verifyMac(&pfx.MacData, pfx.AuthSafe.Content.Bytes, password) + } + if err != nil { + return nil, nil, err + } + } + + var authenticatedSafe []contentInfo + if err := unmarshal(pfx.AuthSafe.Content.Bytes, &authenticatedSafe); err != nil { + return nil, nil, err + } + + if len(authenticatedSafe) != 2 { + return nil, nil, NotImplementedError("expected exactly two items in the authenticated safe") + } + + for _, ci := range authenticatedSafe { + var data []byte + + switch { + case ci.ContentType.Equal(oidDataContentType): + if err := unmarshal(ci.Content.Bytes, &data); err != nil { + return nil, nil, err + } + case ci.ContentType.Equal(oidEncryptedDataContentType): + var encryptedData encryptedData + if err := unmarshal(ci.Content.Bytes, &encryptedData); err != nil { + return nil, nil, err + } + if encryptedData.Version != 0 { + return nil, nil, NotImplementedError("only version 0 of EncryptedData is supported") + } + if data, err = pbDecrypt(encryptedData.EncryptedContentInfo, password); err != nil { + return nil, nil, err + } + default: + return nil, nil, NotImplementedError("only data and encryptedData content types are supported in authenticated safe") + } + + var safeContents []safeBag + if err := unmarshal(data, &safeContents); err != nil { + return nil, nil, err + } + bags = append(bags, safeContents...) + } + + return bags, password, nil +} diff --git a/vendor/golang.org/x/crypto/pkcs12/safebags.go b/vendor/golang.org/x/crypto/pkcs12/safebags.go new file mode 100644 index 000000000000..def1f7b98d7d --- /dev/null +++ b/vendor/golang.org/x/crypto/pkcs12/safebags.go @@ -0,0 +1,57 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package pkcs12 + +import ( + "crypto/x509" + "encoding/asn1" + "errors" +) + +var ( + // see https://tools.ietf.org/html/rfc7292#appendix-D + oidCertTypeX509Certificate = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 9, 22, 1}) + oidPKCS8ShroundedKeyBag = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 10, 1, 2}) + oidCertBag = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 10, 1, 3}) +) + +type certBag struct { + Id asn1.ObjectIdentifier + Data []byte `asn1:"tag:0,explicit"` +} + +func decodePkcs8ShroudedKeyBag(asn1Data, password []byte) (privateKey interface{}, err error) { + pkinfo := new(encryptedPrivateKeyInfo) + if err = unmarshal(asn1Data, pkinfo); err != nil { + return nil, errors.New("pkcs12: error decoding PKCS#8 shrouded key bag: " + err.Error()) + } + + pkData, err := pbDecrypt(pkinfo, password) + if err != nil { + return nil, errors.New("pkcs12: error decrypting PKCS#8 shrouded key bag: " + err.Error()) + } + + ret := new(asn1.RawValue) + if err = unmarshal(pkData, ret); err != nil { + return nil, errors.New("pkcs12: error unmarshaling decrypted private key: " + err.Error()) + } + + if privateKey, err = x509.ParsePKCS8PrivateKey(pkData); err != nil { + return nil, errors.New("pkcs12: error parsing PKCS#8 private key: " + err.Error()) + } + + return privateKey, nil +} + +func decodeCertBag(asn1Data []byte) (x509Certificates []byte, err error) { + bag := new(certBag) + if err := unmarshal(asn1Data, bag); err != nil { + return nil, errors.New("pkcs12: error decoding cert bag: " + err.Error()) + } + if !bag.Id.Equal(oidCertTypeX509Certificate) { + return nil, NotImplementedError("only X509 certificates are supported") + } + return bag.Data, nil +}