diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json index d692c879a7c1..a4504146ed9e 100644 --- a/Godeps/Godeps.json +++ b/Godeps/Godeps.json @@ -30,61 +30,66 @@ }, { "ImportPath": "github.com/Azure/azure-sdk-for-go/arm/compute", - "Comment": "v7.0.1-beta", - "Rev": "0984e0641ae43b89283223034574d6465be93bf4" + "Comment": "v10.0.4-beta-1-g786cc84", + "Rev": "786cc84138518bf7fd6d60e92fad1ac9d1a117ad" }, { "ImportPath": "github.com/Azure/azure-sdk-for-go/arm/containerregistry", - "Comment": "v7.0.1-beta", - "Rev": "0984e0641ae43b89283223034574d6465be93bf4" + "Comment": "v10.0.4-beta-1-g786cc84", + "Rev": "786cc84138518bf7fd6d60e92fad1ac9d1a117ad" }, { "ImportPath": "github.com/Azure/azure-sdk-for-go/arm/network", - "Comment": "v7.0.1-beta", - "Rev": "0984e0641ae43b89283223034574d6465be93bf4" + "Comment": "v10.0.4-beta-1-g786cc84", + "Rev": "786cc84138518bf7fd6d60e92fad1ac9d1a117ad" }, { "ImportPath": "github.com/Azure/azure-sdk-for-go/arm/storage", - "Comment": "v7.0.1-beta", - "Rev": "0984e0641ae43b89283223034574d6465be93bf4" + "Comment": "v10.0.4-beta-1-g786cc84", + "Rev": "786cc84138518bf7fd6d60e92fad1ac9d1a117ad" }, { "ImportPath": "github.com/Azure/azure-sdk-for-go/storage", - "Comment": "v7.0.1-beta", - "Rev": "0984e0641ae43b89283223034574d6465be93bf4" + "Comment": "v10.0.4-beta-1-g786cc84", + "Rev": "786cc84138518bf7fd6d60e92fad1ac9d1a117ad" }, { "ImportPath": "github.com/Azure/go-ansiterm", - "Rev": "70b2c90b260171e829f1ebd7c17f600c11858dbe" + "Rev": "fa152c58bc15761d0200cb75fe958b89a9d4888e" }, { "ImportPath": "github.com/Azure/go-ansiterm/winterm", - "Rev": "70b2c90b260171e829f1ebd7c17f600c11858dbe" + "Rev": "fa152c58bc15761d0200cb75fe958b89a9d4888e" }, { "ImportPath": "github.com/Azure/go-autorest/autorest", - "Comment": "v7.2.3", - "Rev": "d7c034a8af24eda120dd6460bfcd6d9ed14e43ca" + "Comment": "v8.0.0", + "Rev": "58f6f26e200fa5dfb40c9cd1c83f3e2c860d779d" + }, + { + "ImportPath": "github.com/Azure/go-autorest/autorest/adal", + "Comment": "v8.0.0", + "Rev": "58f6f26e200fa5dfb40c9cd1c83f3e2c860d779d" }, { "ImportPath": "github.com/Azure/go-autorest/autorest/azure", - "Comment": "v7.2.3", - "Rev": "d7c034a8af24eda120dd6460bfcd6d9ed14e43ca" + "Comment": "v8.0.0", + "Rev": "58f6f26e200fa5dfb40c9cd1c83f3e2c860d779d" }, { "ImportPath": "github.com/Azure/go-autorest/autorest/date", - "Comment": "v7.2.3", - "Rev": "d7c034a8af24eda120dd6460bfcd6d9ed14e43ca" + "Comment": "v8.0.0", + "Rev": "58f6f26e200fa5dfb40c9cd1c83f3e2c860d779d" }, { "ImportPath": "github.com/Azure/go-autorest/autorest/to", - "Comment": "v7.2.3", - "Rev": "d7c034a8af24eda120dd6460bfcd6d9ed14e43ca" + "Comment": "v8.0.0", + "Rev": "58f6f26e200fa5dfb40c9cd1c83f3e2c860d779d" }, { "ImportPath": "github.com/Azure/go-autorest/autorest/validation", - "Comment": "v7.2.3", - "Rev": "d7c034a8af24eda120dd6460bfcd6d9ed14e43ca" + "Comment": "v8.0.0", + "Rev": "58f6f26e200fa5dfb40c9cd1c83f3e2c860d779d" }, { "ImportPath": "github.com/MakeNowJust/heredoc", @@ -1080,127 +1085,127 @@ }, { "ImportPath": "github.com/gogo/protobuf/gogoproto", - "Comment": "v0.4-3-gc0656ed", + "Comment": "v0.4-3-gc0656edd", "Rev": "c0656edd0d9eab7c66d1eb0c568f9039345796f7" }, { "ImportPath": "github.com/gogo/protobuf/plugin/compare", - "Comment": "v0.4-3-gc0656ed", + "Comment": "v0.4-3-gc0656edd", "Rev": "c0656edd0d9eab7c66d1eb0c568f9039345796f7" }, { "ImportPath": "github.com/gogo/protobuf/plugin/defaultcheck", - "Comment": "v0.4-3-gc0656ed", + "Comment": "v0.4-3-gc0656edd", "Rev": "c0656edd0d9eab7c66d1eb0c568f9039345796f7" }, { "ImportPath": "github.com/gogo/protobuf/plugin/description", - "Comment": "v0.4-3-gc0656ed", + "Comment": "v0.4-3-gc0656edd", "Rev": "c0656edd0d9eab7c66d1eb0c568f9039345796f7" }, { "ImportPath": "github.com/gogo/protobuf/plugin/embedcheck", - "Comment": "v0.4-3-gc0656ed", + "Comment": "v0.4-3-gc0656edd", "Rev": "c0656edd0d9eab7c66d1eb0c568f9039345796f7" }, { "ImportPath": "github.com/gogo/protobuf/plugin/enumstringer", - "Comment": "v0.4-3-gc0656ed", + "Comment": "v0.4-3-gc0656edd", "Rev": "c0656edd0d9eab7c66d1eb0c568f9039345796f7" }, { "ImportPath": "github.com/gogo/protobuf/plugin/equal", - "Comment": "v0.4-3-gc0656ed", + "Comment": "v0.4-3-gc0656edd", "Rev": "c0656edd0d9eab7c66d1eb0c568f9039345796f7" }, { "ImportPath": "github.com/gogo/protobuf/plugin/face", - "Comment": "v0.4-3-gc0656ed", + "Comment": "v0.4-3-gc0656edd", "Rev": "c0656edd0d9eab7c66d1eb0c568f9039345796f7" }, { "ImportPath": "github.com/gogo/protobuf/plugin/gostring", - "Comment": "v0.4-3-gc0656ed", + "Comment": "v0.4-3-gc0656edd", "Rev": "c0656edd0d9eab7c66d1eb0c568f9039345796f7" }, { "ImportPath": "github.com/gogo/protobuf/plugin/marshalto", - "Comment": "v0.4-3-gc0656ed", + "Comment": "v0.4-3-gc0656edd", "Rev": "c0656edd0d9eab7c66d1eb0c568f9039345796f7" }, { "ImportPath": "github.com/gogo/protobuf/plugin/oneofcheck", - "Comment": "v0.4-3-gc0656ed", + "Comment": "v0.4-3-gc0656edd", "Rev": "c0656edd0d9eab7c66d1eb0c568f9039345796f7" }, { "ImportPath": "github.com/gogo/protobuf/plugin/populate", - "Comment": "v0.4-3-gc0656ed", + "Comment": "v0.4-3-gc0656edd", "Rev": "c0656edd0d9eab7c66d1eb0c568f9039345796f7" }, { "ImportPath": "github.com/gogo/protobuf/plugin/size", - "Comment": "v0.4-3-gc0656ed", + "Comment": "v0.4-3-gc0656edd", "Rev": "c0656edd0d9eab7c66d1eb0c568f9039345796f7" }, { "ImportPath": "github.com/gogo/protobuf/plugin/stringer", - "Comment": "v0.4-3-gc0656ed", + "Comment": "v0.4-3-gc0656edd", "Rev": "c0656edd0d9eab7c66d1eb0c568f9039345796f7" }, { "ImportPath": "github.com/gogo/protobuf/plugin/testgen", - "Comment": "v0.4-3-gc0656ed", + "Comment": "v0.4-3-gc0656edd", "Rev": "c0656edd0d9eab7c66d1eb0c568f9039345796f7" }, { "ImportPath": "github.com/gogo/protobuf/plugin/union", - "Comment": "v0.4-3-gc0656ed", + "Comment": "v0.4-3-gc0656edd", "Rev": "c0656edd0d9eab7c66d1eb0c568f9039345796f7" }, { "ImportPath": "github.com/gogo/protobuf/plugin/unmarshal", - "Comment": "v0.4-3-gc0656ed", + "Comment": "v0.4-3-gc0656edd", "Rev": "c0656edd0d9eab7c66d1eb0c568f9039345796f7" }, { "ImportPath": "github.com/gogo/protobuf/proto", - "Comment": "v0.4-3-gc0656ed", + "Comment": "v0.4-3-gc0656edd", "Rev": "c0656edd0d9eab7c66d1eb0c568f9039345796f7" }, { "ImportPath": "github.com/gogo/protobuf/protoc-gen-gogo/descriptor", - "Comment": "v0.4-3-gc0656ed", + "Comment": "v0.4-3-gc0656edd", "Rev": "c0656edd0d9eab7c66d1eb0c568f9039345796f7" }, { "ImportPath": "github.com/gogo/protobuf/protoc-gen-gogo/generator", - "Comment": "v0.4-3-gc0656ed", + "Comment": "v0.4-3-gc0656edd", "Rev": "c0656edd0d9eab7c66d1eb0c568f9039345796f7" }, { "ImportPath": "github.com/gogo/protobuf/protoc-gen-gogo/grpc", - "Comment": "v0.4-3-gc0656ed", + "Comment": "v0.4-3-gc0656edd", "Rev": "c0656edd0d9eab7c66d1eb0c568f9039345796f7" }, { "ImportPath": "github.com/gogo/protobuf/protoc-gen-gogo/plugin", - "Comment": "v0.4-3-gc0656ed", + "Comment": "v0.4-3-gc0656edd", "Rev": "c0656edd0d9eab7c66d1eb0c568f9039345796f7" }, { "ImportPath": "github.com/gogo/protobuf/sortkeys", - "Comment": "v0.4-3-gc0656ed", + "Comment": "v0.4-3-gc0656edd", "Rev": "c0656edd0d9eab7c66d1eb0c568f9039345796f7" }, { "ImportPath": "github.com/gogo/protobuf/vanity", - "Comment": "v0.4-3-gc0656ed", + "Comment": "v0.4-3-gc0656edd", "Rev": "c0656edd0d9eab7c66d1eb0c568f9039345796f7" }, { "ImportPath": "github.com/gogo/protobuf/vanity/command", - "Comment": "v0.4-3-gc0656ed", + "Comment": "v0.4-3-gc0656edd", "Rev": "c0656edd0d9eab7c66d1eb0c568f9039345796f7" }, { @@ -1687,17 +1692,17 @@ }, { "ImportPath": "github.com/heketi/heketi/client/api/go-client", - "Comment": "2017-06-21T10:47:05Z", + "Comment": "v4.0.0-95-gaaf4061", "Rev": "aaf40619d85fda757e7a1c1ea1b5118cea65594b" }, { "ImportPath": "github.com/heketi/heketi/pkg/glusterfs/api", - "Comment": "2017-06-21T10:47:05Z", + "Comment": "v4.0.0-95-gaaf4061", "Rev": "aaf40619d85fda757e7a1c1ea1b5118cea65594b" }, { "ImportPath": "github.com/heketi/heketi/pkg/utils", - "Comment": "2017-06-21T10:47:05Z", + "Comment": "v4.0.0-95-gaaf4061", "Rev": "aaf40619d85fda757e7a1c1ea1b5118cea65594b" }, { @@ -2140,7 +2145,6 @@ }, { "ImportPath": "github.com/pelletier/go-buffruneio", - "Comment": "v0.1.0", "Rev": "df1e16fde7fc330a0ca68167c23bf7ed6ac31d6d" }, { @@ -2202,107 +2206,107 @@ }, { "ImportPath": "github.com/rackspace/gophercloud", - "Comment": "v1.0.0-1012-ge00690e", + "Comment": "v1.0.0-1012-ge00690e8", "Rev": "e00690e87603abe613e9f02c816c7c4bef82e063" }, { "ImportPath": "github.com/rackspace/gophercloud/openstack", - "Comment": "v1.0.0-1012-ge00690e", + "Comment": "v1.0.0-1012-ge00690e8", "Rev": "e00690e87603abe613e9f02c816c7c4bef82e063" }, { "ImportPath": "github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes", - "Comment": "v1.0.0-1012-ge00690e", + "Comment": "v1.0.0-1012-ge00690e8", "Rev": "e00690e87603abe613e9f02c816c7c4bef82e063" }, { "ImportPath": "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/bootfromvolume", - "Comment": "v1.0.0-1012-ge00690e", + "Comment": "v1.0.0-1012-ge00690e8", "Rev": "e00690e87603abe613e9f02c816c7c4bef82e063" }, { "ImportPath": "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/diskconfig", - "Comment": "v1.0.0-1012-ge00690e", + "Comment": "v1.0.0-1012-ge00690e8", "Rev": "e00690e87603abe613e9f02c816c7c4bef82e063" }, { "ImportPath": "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach", - "Comment": "v1.0.0-1012-ge00690e", + "Comment": "v1.0.0-1012-ge00690e8", "Rev": "e00690e87603abe613e9f02c816c7c4bef82e063" }, { "ImportPath": "github.com/rackspace/gophercloud/openstack/compute/v2/flavors", - "Comment": "v1.0.0-1012-ge00690e", + "Comment": "v1.0.0-1012-ge00690e8", "Rev": "e00690e87603abe613e9f02c816c7c4bef82e063" }, { "ImportPath": "github.com/rackspace/gophercloud/openstack/compute/v2/images", - "Comment": "v1.0.0-1012-ge00690e", + "Comment": "v1.0.0-1012-ge00690e8", "Rev": "e00690e87603abe613e9f02c816c7c4bef82e063" }, { "ImportPath": "github.com/rackspace/gophercloud/openstack/compute/v2/servers", - "Comment": "v1.0.0-1012-ge00690e", + "Comment": "v1.0.0-1012-ge00690e8", "Rev": "e00690e87603abe613e9f02c816c7c4bef82e063" }, { "ImportPath": "github.com/rackspace/gophercloud/openstack/identity/v2/tenants", - "Comment": "v1.0.0-1012-ge00690e", + "Comment": "v1.0.0-1012-ge00690e8", "Rev": "e00690e87603abe613e9f02c816c7c4bef82e063" }, { "ImportPath": "github.com/rackspace/gophercloud/openstack/identity/v2/tokens", - "Comment": "v1.0.0-1012-ge00690e", + "Comment": "v1.0.0-1012-ge00690e8", "Rev": "e00690e87603abe613e9f02c816c7c4bef82e063" }, { "ImportPath": "github.com/rackspace/gophercloud/openstack/identity/v3/tokens", - "Comment": "v1.0.0-1012-ge00690e", + "Comment": "v1.0.0-1012-ge00690e8", "Rev": "e00690e87603abe613e9f02c816c7c4bef82e063" }, { "ImportPath": "github.com/rackspace/gophercloud/openstack/utils", - "Comment": "v1.0.0-1012-ge00690e", + "Comment": "v1.0.0-1012-ge00690e8", "Rev": "e00690e87603abe613e9f02c816c7c4bef82e063" }, { "ImportPath": "github.com/rackspace/gophercloud/pagination", - "Comment": "v1.0.0-1012-ge00690e", + "Comment": "v1.0.0-1012-ge00690e8", "Rev": "e00690e87603abe613e9f02c816c7c4bef82e063" }, { "ImportPath": "github.com/rackspace/gophercloud/rackspace", - "Comment": "v1.0.0-1012-ge00690e", + "Comment": "v1.0.0-1012-ge00690e8", "Rev": "e00690e87603abe613e9f02c816c7c4bef82e063" }, { "ImportPath": "github.com/rackspace/gophercloud/rackspace/blockstorage/v1/volumes", - "Comment": "v1.0.0-1012-ge00690e", + "Comment": "v1.0.0-1012-ge00690e8", "Rev": "e00690e87603abe613e9f02c816c7c4bef82e063" }, { "ImportPath": "github.com/rackspace/gophercloud/rackspace/compute/v2/servers", - "Comment": "v1.0.0-1012-ge00690e", + "Comment": "v1.0.0-1012-ge00690e8", "Rev": "e00690e87603abe613e9f02c816c7c4bef82e063" }, { "ImportPath": "github.com/rackspace/gophercloud/rackspace/compute/v2/volumeattach", - "Comment": "v1.0.0-1012-ge00690e", + "Comment": "v1.0.0-1012-ge00690e8", "Rev": "e00690e87603abe613e9f02c816c7c4bef82e063" }, { "ImportPath": "github.com/rackspace/gophercloud/rackspace/identity/v2/tokens", - "Comment": "v1.0.0-1012-ge00690e", + "Comment": "v1.0.0-1012-ge00690e8", "Rev": "e00690e87603abe613e9f02c816c7c4bef82e063" }, { "ImportPath": "github.com/rackspace/gophercloud/testhelper", - "Comment": "v1.0.0-1012-ge00690e", + "Comment": "v1.0.0-1012-ge00690e8", "Rev": "e00690e87603abe613e9f02c816c7c4bef82e063" }, { "ImportPath": "github.com/rackspace/gophercloud/testhelper/client", - "Comment": "v1.0.0-1012-ge00690e", + "Comment": "v1.0.0-1012-ge00690e8", "Rev": "e00690e87603abe613e9f02c816c7c4bef82e063" }, { @@ -2329,6 +2333,11 @@ "Comment": "v1.4-2-g300106c", "Rev": "300106c228d52c8941d4b3de6054a6062a86dda3" }, + { + "ImportPath": "github.com/satori/uuid", + "Comment": "v1.1.0-8-g5bf94b6", + "Rev": "5bf94b69c6b68ee1b541973bb8e1144db23a194b" + }, { "ImportPath": "github.com/seccomp/libseccomp-golang", "Rev": "1b506fc7c24eec5a3693cdcbed40d9c226cfc6a1" @@ -2544,7 +2553,6 @@ }, { "ImportPath": "github.com/xiang90/probing", - "Comment": "0.0.1", "Rev": "07dd2e8dfe18522e9c447ba95f2fe95262f63bb2" }, { diff --git a/Godeps/LICENSES b/Godeps/LICENSES index ab02b1c52d39..a2eebe99f89b 100644 --- a/Godeps/LICENSES +++ b/Godeps/LICENSES @@ -9839,6 +9839,205 @@ THE SOFTWARE. ================================================================================ +================================================================================ += vendor/github.com/Azure/go-autorest/autorest/adal licensed under: = + + + 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. + += vendor/github.com/Azure/go-autorest/LICENSE a250e5ac3848f2acadb5adcb9555c18b - +================================================================================ + + ================================================================================ = vendor/github.com/Azure/go-autorest/autorest/azure licensed under: = @@ -74314,6 +74513,34 @@ Blackfriday is distributed under the Simplified BSD License: ================================================================================ +================================================================================ += vendor/github.com/satori/uuid licensed under: = + +Copyright (C) 2013-2016 by Maxim Bublis + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + += vendor/github.com/satori/uuid/LICENSE 02d5d17de0c82a23a09863acccc026f6 - +================================================================================ + + ================================================================================ = vendor/github.com/seccomp/libseccomp-golang licensed under: = diff --git a/pkg/cloudprovider/providers/azure/BUILD b/pkg/cloudprovider/providers/azure/BUILD index 4e68e86fdd69..75848013e5d3 100644 --- a/pkg/cloudprovider/providers/azure/BUILD +++ b/pkg/cloudprovider/providers/azure/BUILD @@ -37,6 +37,7 @@ go_library( "//vendor/github.com/Azure/azure-sdk-for-go/arm/storage:go_default_library", "//vendor/github.com/Azure/azure-sdk-for-go/storage:go_default_library", "//vendor/github.com/Azure/go-autorest/autorest:go_default_library", + "//vendor/github.com/Azure/go-autorest/autorest/adal:go_default_library", "//vendor/github.com/Azure/go-autorest/autorest/azure:go_default_library", "//vendor/github.com/Azure/go-autorest/autorest/to:go_default_library", "//vendor/github.com/ghodss/yaml:go_default_library", diff --git a/pkg/cloudprovider/providers/azure/azure.go b/pkg/cloudprovider/providers/azure/azure.go index 83dab01a084c..daba02d13b91 100644 --- a/pkg/cloudprovider/providers/azure/azure.go +++ b/pkg/cloudprovider/providers/azure/azure.go @@ -33,6 +33,7 @@ import ( "github.com/Azure/azure-sdk-for-go/arm/network" "github.com/Azure/azure-sdk-for-go/arm/storage" "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/adal" "github.com/Azure/go-autorest/autorest/azure" "github.com/ghodss/yaml" "github.com/golang/glog" @@ -142,14 +143,14 @@ func decodePkcs12(pkcs []byte, password string) (*x509.Certificate, *rsa.Private } // newServicePrincipalToken creates a new service principal token based on the configuration -func newServicePrincipalToken(az *Cloud) (*azure.ServicePrincipalToken, error) { - oauthConfig, err := az.Environment.OAuthConfigForTenant(az.TenantID) +func newServicePrincipalToken(az *Cloud) (*adal.ServicePrincipalToken, error) { + oauthConfig, err := adal.NewOAuthConfig(az.Environment.ActiveDirectoryEndpoint, az.TenantID) if err != nil { return nil, fmt.Errorf("creating the OAuth config: %v", err) } if len(az.AADClientSecret) > 0 { - return azure.NewServicePrincipalToken( + return adal.NewServicePrincipalToken( *oauthConfig, az.AADClientID, az.AADClientSecret, @@ -163,7 +164,7 @@ func newServicePrincipalToken(az *Cloud) (*azure.ServicePrincipalToken, error) { if err != nil { return nil, fmt.Errorf("decoding the client certificate: %v", err) } - return azure.NewServicePrincipalTokenFromCertificate( + return adal.NewServicePrincipalTokenFromCertificate( *oauthConfig, az.AADClientID, certificate, @@ -203,54 +204,54 @@ func NewCloud(configReader io.Reader) (cloudprovider.Interface, error) { az.SubnetsClient = network.NewSubnetsClient(az.SubscriptionID) az.SubnetsClient.BaseURI = az.Environment.ResourceManagerEndpoint - az.SubnetsClient.Authorizer = servicePrincipalToken + az.SubnetsClient.Authorizer = autorest.NewBearerAuthorizer(servicePrincipalToken) az.SubnetsClient.PollingDelay = 5 * time.Second configureUserAgent(&az.SubnetsClient.Client) az.RouteTablesClient = network.NewRouteTablesClient(az.SubscriptionID) az.RouteTablesClient.BaseURI = az.Environment.ResourceManagerEndpoint - az.RouteTablesClient.Authorizer = servicePrincipalToken + az.RouteTablesClient.Authorizer = autorest.NewBearerAuthorizer(servicePrincipalToken) az.RouteTablesClient.PollingDelay = 5 * time.Second configureUserAgent(&az.RouteTablesClient.Client) az.RoutesClient = network.NewRoutesClient(az.SubscriptionID) az.RoutesClient.BaseURI = az.Environment.ResourceManagerEndpoint - az.RoutesClient.Authorizer = servicePrincipalToken + az.RoutesClient.Authorizer = autorest.NewBearerAuthorizer(servicePrincipalToken) az.RoutesClient.PollingDelay = 5 * time.Second configureUserAgent(&az.RoutesClient.Client) az.InterfacesClient = network.NewInterfacesClient(az.SubscriptionID) az.InterfacesClient.BaseURI = az.Environment.ResourceManagerEndpoint - az.InterfacesClient.Authorizer = servicePrincipalToken + az.InterfacesClient.Authorizer = autorest.NewBearerAuthorizer(servicePrincipalToken) az.InterfacesClient.PollingDelay = 5 * time.Second configureUserAgent(&az.InterfacesClient.Client) az.LoadBalancerClient = network.NewLoadBalancersClient(az.SubscriptionID) az.LoadBalancerClient.BaseURI = az.Environment.ResourceManagerEndpoint - az.LoadBalancerClient.Authorizer = servicePrincipalToken + az.LoadBalancerClient.Authorizer = autorest.NewBearerAuthorizer(servicePrincipalToken) az.LoadBalancerClient.PollingDelay = 5 * time.Second configureUserAgent(&az.LoadBalancerClient.Client) az.VirtualMachinesClient = compute.NewVirtualMachinesClient(az.SubscriptionID) az.VirtualMachinesClient.BaseURI = az.Environment.ResourceManagerEndpoint - az.VirtualMachinesClient.Authorizer = servicePrincipalToken + az.VirtualMachinesClient.Authorizer = autorest.NewBearerAuthorizer(servicePrincipalToken) az.VirtualMachinesClient.PollingDelay = 5 * time.Second configureUserAgent(&az.VirtualMachinesClient.Client) az.PublicIPAddressesClient = network.NewPublicIPAddressesClient(az.SubscriptionID) az.PublicIPAddressesClient.BaseURI = az.Environment.ResourceManagerEndpoint - az.PublicIPAddressesClient.Authorizer = servicePrincipalToken + az.PublicIPAddressesClient.Authorizer = autorest.NewBearerAuthorizer(servicePrincipalToken) az.PublicIPAddressesClient.PollingDelay = 5 * time.Second configureUserAgent(&az.PublicIPAddressesClient.Client) az.SecurityGroupsClient = network.NewSecurityGroupsClient(az.SubscriptionID) az.SecurityGroupsClient.BaseURI = az.Environment.ResourceManagerEndpoint - az.SecurityGroupsClient.Authorizer = servicePrincipalToken + az.SecurityGroupsClient.Authorizer = autorest.NewBearerAuthorizer(servicePrincipalToken) az.SecurityGroupsClient.PollingDelay = 5 * time.Second configureUserAgent(&az.SecurityGroupsClient.Client) az.StorageAccountClient = storage.NewAccountsClientWithBaseURI(az.Environment.ResourceManagerEndpoint, az.SubscriptionID) - az.StorageAccountClient.Authorizer = servicePrincipalToken + az.StorageAccountClient.Authorizer = autorest.NewBearerAuthorizer(servicePrincipalToken) // Conditionally configure rate limits if az.CloudProviderRateLimit { diff --git a/pkg/cloudprovider/providers/azure/azure_backoff.go b/pkg/cloudprovider/providers/azure/azure_backoff.go index 3fca4c49334b..839592f30352 100644 --- a/pkg/cloudprovider/providers/azure/azure_backoff.go +++ b/pkg/cloudprovider/providers/azure/azure_backoff.go @@ -47,8 +47,10 @@ func (az *Cloud) GetVirtualMachineWithRetry(name types.NodeName) (compute.Virtua func (az *Cloud) CreateOrUpdateSGWithRetry(sg network.SecurityGroup) error { return wait.ExponentialBackoff(az.resourceRequestBackoff, func() (bool, error) { az.operationPollRateLimiter.Accept() - resp, err := az.SecurityGroupsClient.CreateOrUpdate(az.ResourceGroup, *sg.Name, sg, nil) - return processRetryResponse(resp, err) + respChan, errChan := az.SecurityGroupsClient.CreateOrUpdate(az.ResourceGroup, *sg.Name, sg, nil) + resp := <-respChan + err := <-errChan + return processRetryResponse(resp.Response, err) }) } @@ -56,8 +58,10 @@ func (az *Cloud) CreateOrUpdateSGWithRetry(sg network.SecurityGroup) error { func (az *Cloud) CreateOrUpdateLBWithRetry(lb network.LoadBalancer) error { return wait.ExponentialBackoff(az.resourceRequestBackoff, func() (bool, error) { az.operationPollRateLimiter.Accept() - resp, err := az.LoadBalancerClient.CreateOrUpdate(az.ResourceGroup, *lb.Name, lb, nil) - return processRetryResponse(resp, err) + respChan, errChan := az.LoadBalancerClient.CreateOrUpdate(az.ResourceGroup, *lb.Name, lb, nil) + resp := <-respChan + err := <-errChan + return processRetryResponse(resp.Response, err) }) } @@ -65,8 +69,10 @@ func (az *Cloud) CreateOrUpdateLBWithRetry(lb network.LoadBalancer) error { func (az *Cloud) CreateOrUpdatePIPWithRetry(pip network.PublicIPAddress) error { return wait.ExponentialBackoff(az.resourceRequestBackoff, func() (bool, error) { az.operationPollRateLimiter.Accept() - resp, err := az.PublicIPAddressesClient.CreateOrUpdate(az.ResourceGroup, *pip.Name, pip, nil) - return processRetryResponse(resp, err) + respChan, errChan := az.PublicIPAddressesClient.CreateOrUpdate(az.ResourceGroup, *pip.Name, pip, nil) + resp := <-respChan + err := <-errChan + return processRetryResponse(resp.Response, err) }) } @@ -74,8 +80,10 @@ func (az *Cloud) CreateOrUpdatePIPWithRetry(pip network.PublicIPAddress) error { func (az *Cloud) CreateOrUpdateInterfaceWithRetry(nic network.Interface) error { return wait.ExponentialBackoff(az.resourceRequestBackoff, func() (bool, error) { az.operationPollRateLimiter.Accept() - resp, err := az.InterfacesClient.CreateOrUpdate(az.ResourceGroup, *nic.Name, nic, nil) - return processRetryResponse(resp, err) + respChan, errChan := az.InterfacesClient.CreateOrUpdate(az.ResourceGroup, *nic.Name, nic, nil) + resp := <-respChan + err := <-errChan + return processRetryResponse(resp.Response, err) }) } @@ -83,7 +91,9 @@ func (az *Cloud) CreateOrUpdateInterfaceWithRetry(nic network.Interface) error { func (az *Cloud) DeletePublicIPWithRetry(pipName string) error { return wait.ExponentialBackoff(az.resourceRequestBackoff, func() (bool, error) { az.operationPollRateLimiter.Accept() - resp, err := az.PublicIPAddressesClient.Delete(az.ResourceGroup, pipName, nil) + respChan, errChan := az.PublicIPAddressesClient.Delete(az.ResourceGroup, pipName, nil) + resp := <-respChan + err := <-errChan return processRetryResponse(resp, err) }) } @@ -92,7 +102,9 @@ func (az *Cloud) DeletePublicIPWithRetry(pipName string) error { func (az *Cloud) DeleteLBWithRetry(lbName string) error { return wait.ExponentialBackoff(az.resourceRequestBackoff, func() (bool, error) { az.operationPollRateLimiter.Accept() - resp, err := az.LoadBalancerClient.Delete(az.ResourceGroup, lbName, nil) + respChan, errChan := az.LoadBalancerClient.Delete(az.ResourceGroup, lbName, nil) + resp := <-respChan + err := <-errChan return processRetryResponse(resp, err) }) } @@ -101,8 +113,10 @@ func (az *Cloud) DeleteLBWithRetry(lbName string) error { func (az *Cloud) CreateOrUpdateRouteTableWithRetry(routeTable network.RouteTable) error { return wait.ExponentialBackoff(az.resourceRequestBackoff, func() (bool, error) { az.operationPollRateLimiter.Accept() - resp, err := az.RouteTablesClient.CreateOrUpdate(az.ResourceGroup, az.RouteTableName, routeTable, nil) - return processRetryResponse(resp, err) + respChan, errChan := az.RouteTablesClient.CreateOrUpdate(az.ResourceGroup, az.RouteTableName, routeTable, nil) + resp := <-respChan + err := <-errChan + return processRetryResponse(resp.Response, err) }) } @@ -110,8 +124,10 @@ func (az *Cloud) CreateOrUpdateRouteTableWithRetry(routeTable network.RouteTable func (az *Cloud) CreateOrUpdateRouteWithRetry(route network.Route) error { return wait.ExponentialBackoff(az.resourceRequestBackoff, func() (bool, error) { az.operationPollRateLimiter.Accept() - resp, err := az.RoutesClient.CreateOrUpdate(az.ResourceGroup, az.RouteTableName, *route.Name, route, nil) - return processRetryResponse(resp, err) + respChan, errChan := az.RoutesClient.CreateOrUpdate(az.ResourceGroup, az.RouteTableName, *route.Name, route, nil) + resp := <-respChan + err := <-errChan + return processRetryResponse(resp.Response, err) }) } @@ -119,7 +135,9 @@ func (az *Cloud) CreateOrUpdateRouteWithRetry(route network.Route) error { func (az *Cloud) DeleteRouteWithRetry(routeName string) error { return wait.ExponentialBackoff(az.resourceRequestBackoff, func() (bool, error) { az.operationPollRateLimiter.Accept() - resp, err := az.RoutesClient.Delete(az.ResourceGroup, az.RouteTableName, routeName, nil) + respChan, errChan := az.RoutesClient.Delete(az.ResourceGroup, az.RouteTableName, routeName, nil) + resp := <-respChan + err := <-errChan return processRetryResponse(resp, err) }) } @@ -128,8 +146,10 @@ func (az *Cloud) DeleteRouteWithRetry(routeName string) error { func (az *Cloud) CreateOrUpdateVMWithRetry(vmName string, newVM compute.VirtualMachine) error { return wait.ExponentialBackoff(az.resourceRequestBackoff, func() (bool, error) { az.operationPollRateLimiter.Accept() - resp, err := az.VirtualMachinesClient.CreateOrUpdate(az.ResourceGroup, vmName, newVM, nil) - return processRetryResponse(resp, err) + respChan, errChan := az.VirtualMachinesClient.CreateOrUpdate(az.ResourceGroup, vmName, newVM, nil) + resp := <-respChan + err := <-errChan + return processRetryResponse(resp.Response, err) }) } diff --git a/pkg/cloudprovider/providers/azure/azure_blob.go b/pkg/cloudprovider/providers/azure/azure_blob.go index 47d1edd130f8..bf3e8de39aaa 100644 --- a/pkg/cloudprovider/providers/azure/azure_blob.go +++ b/pkg/cloudprovider/providers/azure/azure_blob.go @@ -21,6 +21,8 @@ import ( "regexp" "strings" + "bytes" + azs "github.com/Azure/azure-sdk-for-go/storage" ) @@ -40,14 +42,21 @@ func (az *Cloud) createVhdBlob(accountName, accountKey, name string, sizeGB int6 vhdSize := size + vhdHeaderSize /* header size */ // Blob name in URL must end with '.vhd' extension. name = name + ".vhd" - err = blobClient.PutPageBlob(vhdContainerName, name, vhdSize, tags) + cnt := blobClient.GetContainerReference(vhdContainerName) + b := cnt.GetBlobReference(name) + b.Properties.ContentLength = vhdSize + b.Metadata = tags + err = b.PutPageBlob(nil) if err != nil { // if container doesn't exist, create one and retry PutPageBlob detail := err.Error() if strings.Contains(detail, errContainerNotFound) { - err = blobClient.CreateContainer(vhdContainerName, azs.ContainerAccessTypePrivate) + err = cnt.Create(&azs.CreateContainerOptions{Access: azs.ContainerAccessTypePrivate}) if err == nil { - err = blobClient.PutPageBlob(vhdContainerName, name, vhdSize, tags) + b := cnt.GetBlobReference(name) + b.Properties.ContentLength = vhdSize + b.Metadata = tags + err = b.PutPageBlob(nil) } } } @@ -61,7 +70,11 @@ func (az *Cloud) createVhdBlob(accountName, accountKey, name string, sizeGB int6 az.deleteVhdBlob(accountName, accountKey, name) return "", "", fmt.Errorf("failed to create vhd header, err: %v", err) } - if err = blobClient.PutPage(vhdContainerName, name, size, vhdSize-1, azs.PageWriteTypeUpdate, h[:vhdHeaderSize], nil); err != nil { + blobRange := azs.BlobRange{ + Start: uint64(size), + End: uint64(vhdSize - 1), + } + if err = b.WriteRange(blobRange, bytes.NewBuffer(h[:vhdHeaderSize]), nil); err != nil { az.deleteVhdBlob(accountName, accountKey, name) return "", "", fmt.Errorf("failed to update vhd header, err: %v", err) } @@ -80,7 +93,9 @@ func (az *Cloud) createVhdBlob(accountName, accountKey, name string, sizeGB int6 func (az *Cloud) deleteVhdBlob(accountName, accountKey, blobName string) error { blobClient, err := az.getBlobClient(accountName, accountKey) if err == nil { - return blobClient.DeleteBlob(vhdContainerName, blobName, nil) + cnt := blobClient.GetContainerReference(vhdContainerName) + b := cnt.GetBlobReference(blobName) + return b.Delete(nil) } return err } diff --git a/pkg/cloudprovider/providers/azure/azure_file.go b/pkg/cloudprovider/providers/azure/azure_file.go index ccdca622a46a..97beaf670db7 100644 --- a/pkg/cloudprovider/providers/azure/azure_file.go +++ b/pkg/cloudprovider/providers/azure/azure_file.go @@ -18,9 +18,9 @@ package azure import ( "fmt" - "strconv" azs "github.com/Azure/azure-sdk-for-go/storage" + "github.com/golang/glog" ) // create file share @@ -34,11 +34,15 @@ func (az *Cloud) createFileShare(accountName, accountKey, name string, sizeGB in // setting x-ms-share-quota can set quota on the new share, but in reality, setting quota in CreateShare // receives error "The metadata specified is invalid. It has characters that are not permitted." // As a result,breaking into two API calls: create share and set quota - if err = fileClient.CreateShare(name, nil); err != nil { + share := fileClient.GetShareReference(name) + if err = share.Create(nil); err != nil { return fmt.Errorf("failed to create file share, err: %v", err) } - if err = fileClient.SetShareProperties(name, azs.ShareHeaders{Quota: strconv.Itoa(sizeGB)}); err != nil { - az.deleteFileShare(accountName, accountKey, name) + share.Properties.Quota = sizeGB + if err = share.SetProperties(nil); err != nil { + if err := share.Delete(nil); err != nil { + glog.Errorf("Error deleting share: %v", err) + } return fmt.Errorf("failed to set quota on file share %s, err: %v", name, err) } return nil @@ -48,7 +52,8 @@ func (az *Cloud) createFileShare(accountName, accountKey, name string, sizeGB in func (az *Cloud) deleteFileShare(accountName, accountKey, name string) error { fileClient, err := az.getFileSvcClient(accountName, accountKey) if err == nil { - return fileClient.DeleteShare(name) + share := fileClient.GetShareReference(name) + return share.Delete(nil) } return err } diff --git a/pkg/cloudprovider/providers/azure/azure_loadbalancer.go b/pkg/cloudprovider/providers/azure/azure_loadbalancer.go index 4cfede077290..9b959b4e4cbd 100644 --- a/pkg/cloudprovider/providers/azure/azure_loadbalancer.go +++ b/pkg/cloudprovider/providers/azure/azure_loadbalancer.go @@ -143,8 +143,10 @@ func (az *Cloud) EnsureLoadBalancer(clusterName string, service *v1.Service, nod sg.SecurityGroupPropertiesFormat.NetworkInterfaces = nil sg.SecurityGroupPropertiesFormat.Subnets = nil az.operationPollRateLimiter.Accept() - resp, err := az.SecurityGroupsClient.CreateOrUpdate(az.ResourceGroup, *sg.Name, sg, nil) - if az.CloudProviderBackoff && shouldRetryAPIRequest(resp, err) { + respChan, errChan := az.SecurityGroupsClient.CreateOrUpdate(az.ResourceGroup, *sg.Name, sg, nil) + resp := <-respChan + err := <-errChan + if az.CloudProviderBackoff && shouldRetryAPIRequest(resp.Response, err) { glog.V(2).Infof("ensure(%s) backing off: sg(%s) - updating", serviceName, *sg.Name) retryErr := az.CreateOrUpdateSGWithRetry(sg) if retryErr != nil { @@ -222,8 +224,10 @@ func (az *Cloud) EnsureLoadBalancer(clusterName string, service *v1.Service, nod if !existsLb || lbNeedsUpdate { glog.V(3).Infof("ensure(%s): lb(%s) - updating", serviceName, lbName) az.operationPollRateLimiter.Accept() - resp, err := az.LoadBalancerClient.CreateOrUpdate(az.ResourceGroup, *lb.Name, lb, nil) - if az.CloudProviderBackoff && shouldRetryAPIRequest(resp, err) { + respChan, errChan := az.LoadBalancerClient.CreateOrUpdate(az.ResourceGroup, *lb.Name, lb, nil) + resp := <-respChan + err := <-errChan + if az.CloudProviderBackoff && shouldRetryAPIRequest(resp.Response, err) { glog.V(2).Infof("ensure(%s) backing off: lb(%s) - updating", serviceName, lbName) retryErr := az.CreateOrUpdateLBWithRetry(lb) if retryErr != nil { @@ -315,8 +319,10 @@ func (az *Cloud) EnsureLoadBalancerDeleted(clusterName string, service *v1.Servi sg.SecurityGroupPropertiesFormat.NetworkInterfaces = nil sg.SecurityGroupPropertiesFormat.Subnets = nil az.operationPollRateLimiter.Accept() - resp, err := az.SecurityGroupsClient.CreateOrUpdate(az.ResourceGroup, *reconciledSg.Name, reconciledSg, nil) - if az.CloudProviderBackoff && shouldRetryAPIRequest(resp, err) { + respChan, errChan := az.SecurityGroupsClient.CreateOrUpdate(az.ResourceGroup, *reconciledSg.Name, reconciledSg, nil) + resp := <-respChan + err := <-errChan + if az.CloudProviderBackoff && shouldRetryAPIRequest(resp.Response, err) { glog.V(2).Infof("delete(%s) backing off: sg(%s) - updating", serviceName, az.SecurityGroupName) retryErr := az.CreateOrUpdateSGWithRetry(reconciledSg) if retryErr != nil { @@ -369,8 +375,10 @@ func (az *Cloud) cleanupLoadBalancer(clusterName string, service *v1.Service, is if len(*lb.FrontendIPConfigurations) > 0 { glog.V(3).Infof("delete(%s): lb(%s) - updating", serviceName, lbName) az.operationPollRateLimiter.Accept() - resp, err := az.LoadBalancerClient.CreateOrUpdate(az.ResourceGroup, *lb.Name, lb, nil) - if az.CloudProviderBackoff && shouldRetryAPIRequest(resp, err) { + respChan, errChan := az.LoadBalancerClient.CreateOrUpdate(az.ResourceGroup, *lb.Name, lb, nil) + resp := <-respChan + err := <-errChan + if az.CloudProviderBackoff && shouldRetryAPIRequest(resp.Response, err) { glog.V(2).Infof("delete(%s) backing off: sg(%s) - updating", serviceName, az.SecurityGroupName) retryErr := az.CreateOrUpdateLBWithRetry(lb) if retryErr != nil { @@ -385,7 +393,9 @@ func (az *Cloud) cleanupLoadBalancer(clusterName string, service *v1.Service, is glog.V(3).Infof("delete(%s): lb(%s) - deleting; no remaining frontendipconfigs", serviceName, lbName) az.operationPollRateLimiter.Accept() - resp, err := az.LoadBalancerClient.Delete(az.ResourceGroup, lbName, nil) + respChan, errChan := az.LoadBalancerClient.Delete(az.ResourceGroup, lbName, nil) + resp := <-respChan + err := <-errChan if az.CloudProviderBackoff && shouldRetryAPIRequest(resp, err) { glog.V(2).Infof("delete(%s) backing off: lb(%s) - deleting; no remaining frontendipconfigs", serviceName, lbName) retryErr := az.DeleteLBWithRetry(lbName) @@ -440,8 +450,10 @@ func (az *Cloud) ensurePublicIPExists(serviceName, pipName string) (*network.Pub glog.V(3).Infof("ensure(%s): pip(%s) - creating", serviceName, *pip.Name) az.operationPollRateLimiter.Accept() - resp, err := az.PublicIPAddressesClient.CreateOrUpdate(az.ResourceGroup, *pip.Name, pip, nil) - if az.CloudProviderBackoff && shouldRetryAPIRequest(resp, err) { + respChan, errChan := az.PublicIPAddressesClient.CreateOrUpdate(az.ResourceGroup, *pip.Name, pip, nil) + resp := <-respChan + err = <-errChan + if az.CloudProviderBackoff && shouldRetryAPIRequest(resp.Response, err) { glog.V(2).Infof("ensure(%s) backing off: pip(%s) - creating", serviceName, *pip.Name) retryErr := az.CreateOrUpdatePIPWithRetry(pip) if retryErr != nil { @@ -466,8 +478,9 @@ func (az *Cloud) ensurePublicIPExists(serviceName, pipName string) (*network.Pub func (az *Cloud) ensurePublicIPDeleted(serviceName, pipName string) error { glog.V(2).Infof("ensure(%s): pip(%s) - deleting", serviceName, pipName) az.operationPollRateLimiter.Accept() - resp, deleteErr := az.PublicIPAddressesClient.Delete(az.ResourceGroup, pipName, nil) - if az.CloudProviderBackoff && shouldRetryAPIRequest(resp, deleteErr) { + resp, deleteErrChan := az.PublicIPAddressesClient.Delete(az.ResourceGroup, pipName, nil) + deleteErr := <-deleteErrChan + if az.CloudProviderBackoff && shouldRetryAPIRequest(<-resp, deleteErr) { glog.V(2).Infof("ensure(%s) backing off: pip(%s) - deleting", serviceName, pipName) retryErr := az.DeletePublicIPWithRetry(pipName) if retryErr != nil { @@ -772,8 +785,8 @@ func (az *Cloud) reconcileSecurityGroup(sg network.SecurityGroup, clusterName st DestinationPortRange: to.StringPtr(strconv.Itoa(int(port.Port))), SourceAddressPrefix: to.StringPtr(sourceAddressPrefixes[j]), DestinationAddressPrefix: to.StringPtr("*"), - Access: network.Allow, - Direction: network.Inbound, + Access: network.SecurityRuleAccessAllow, + Direction: network.SecurityRuleDirectionInbound, }, } } @@ -918,8 +931,10 @@ func (az *Cloud) ensureHostInPool(serviceName string, nodeName types.NodeName, b glog.V(3).Infof("nicupdate(%s): nic(%s) - updating", serviceName, nicName) az.operationPollRateLimiter.Accept() - resp, err := az.InterfacesClient.CreateOrUpdate(az.ResourceGroup, *nic.Name, nic, nil) - if az.CloudProviderBackoff && shouldRetryAPIRequest(resp, err) { + respChan, errChan := az.InterfacesClient.CreateOrUpdate(az.ResourceGroup, *nic.Name, nic, nil) + resp := <-respChan + err := <-errChan + if az.CloudProviderBackoff && shouldRetryAPIRequest(resp.Response, err) { glog.V(2).Infof("nicupdate(%s) backing off: nic(%s) - updating, err=%v", serviceName, nicName, err) retryErr := az.CreateOrUpdateInterfaceWithRetry(nic) if retryErr != nil { diff --git a/pkg/cloudprovider/providers/azure/azure_routes.go b/pkg/cloudprovider/providers/azure/azure_routes.go index 0d7a23ebfd82..b7cb4ae810f8 100644 --- a/pkg/cloudprovider/providers/azure/azure_routes.go +++ b/pkg/cloudprovider/providers/azure/azure_routes.go @@ -78,8 +78,10 @@ func (az *Cloud) CreateRoute(clusterName string, nameHint string, kubeRoute *clo glog.V(3).Infof("create: creating routetable. routeTableName=%q", az.RouteTableName) az.operationPollRateLimiter.Accept() - resp, err := az.RouteTablesClient.CreateOrUpdate(az.ResourceGroup, az.RouteTableName, routeTable, nil) - if az.CloudProviderBackoff && shouldRetryAPIRequest(resp, err) { + respChan, errChan := az.RouteTablesClient.CreateOrUpdate(az.ResourceGroup, az.RouteTableName, routeTable, nil) + resp := <-respChan + err := <-errChan + if az.CloudProviderBackoff && shouldRetryAPIRequest(resp.Response, err) { glog.V(2).Infof("create backing off: creating routetable. routeTableName=%q", az.RouteTableName) retryErr := az.CreateOrUpdateRouteTableWithRetry(routeTable) if retryErr != nil { @@ -114,8 +116,10 @@ func (az *Cloud) CreateRoute(clusterName string, nameHint string, kubeRoute *clo glog.V(3).Infof("create: creating route: instance=%q cidr=%q", kubeRoute.TargetNode, kubeRoute.DestinationCIDR) az.operationPollRateLimiter.Accept() - resp, err := az.RoutesClient.CreateOrUpdate(az.ResourceGroup, az.RouteTableName, *route.Name, route, nil) - if az.CloudProviderBackoff && shouldRetryAPIRequest(resp, err) { + respChan, errChan := az.RoutesClient.CreateOrUpdate(az.ResourceGroup, az.RouteTableName, *route.Name, route, nil) + resp := <-respChan + err = <-errChan + if az.CloudProviderBackoff && shouldRetryAPIRequest(resp.Response, err) { glog.V(2).Infof("create backing off: creating route: instance=%q cidr=%q", kubeRoute.TargetNode, kubeRoute.DestinationCIDR) retryErr := az.CreateOrUpdateRouteWithRetry(route) if retryErr != nil { @@ -138,7 +142,10 @@ func (az *Cloud) DeleteRoute(clusterName string, kubeRoute *cloudprovider.Route) routeName := mapNodeNameToRouteName(kubeRoute.TargetNode) az.operationPollRateLimiter.Accept() - resp, err := az.RoutesClient.Delete(az.ResourceGroup, az.RouteTableName, routeName, nil) + respChan, errChan := az.RoutesClient.Delete(az.ResourceGroup, az.RouteTableName, routeName, nil) + resp := <-respChan + err := <-errChan + if az.CloudProviderBackoff && shouldRetryAPIRequest(resp, err) { glog.V(2).Infof("delete backing off: deleting route. clusterName=%q instance=%q cidr=%q", clusterName, kubeRoute.TargetNode, kubeRoute.DestinationCIDR) retryErr := az.DeleteRouteWithRetry(routeName) diff --git a/pkg/cloudprovider/providers/azure/azure_storage.go b/pkg/cloudprovider/providers/azure/azure_storage.go index b810480ab478..255d0e1ef110 100644 --- a/pkg/cloudprovider/providers/azure/azure_storage.go +++ b/pkg/cloudprovider/providers/azure/azure_storage.go @@ -66,8 +66,10 @@ func (az *Cloud) AttachDisk(diskName, diskURI string, nodeName types.NodeName, l vmName := mapNodeNameToVMName(nodeName) glog.V(2).Infof("create(%s): vm(%s)", az.ResourceGroup, vmName) az.operationPollRateLimiter.Accept() - resp, err := az.VirtualMachinesClient.CreateOrUpdate(az.ResourceGroup, vmName, newVM, nil) - if az.CloudProviderBackoff && shouldRetryAPIRequest(resp, err) { + respChan, errChan := az.VirtualMachinesClient.CreateOrUpdate(az.ResourceGroup, vmName, newVM, nil) + resp := <-respChan + err = <-errChan + if az.CloudProviderBackoff && shouldRetryAPIRequest(resp.Response, err) { glog.V(2).Infof("create(%s) backing off: vm(%s)", az.ResourceGroup, vmName) retryErr := az.CreateOrUpdateVMWithRetry(vmName, newVM) if retryErr != nil { @@ -147,8 +149,10 @@ func (az *Cloud) DetachDiskByName(diskName, diskURI string, nodeName types.NodeN vmName := mapNodeNameToVMName(nodeName) glog.V(2).Infof("create(%s): vm(%s)", az.ResourceGroup, vmName) az.operationPollRateLimiter.Accept() - resp, err := az.VirtualMachinesClient.CreateOrUpdate(az.ResourceGroup, vmName, newVM, nil) - if az.CloudProviderBackoff && shouldRetryAPIRequest(resp, err) { + respChan, errChan := az.VirtualMachinesClient.CreateOrUpdate(az.ResourceGroup, vmName, newVM, nil) + resp := <-respChan + err = <-errChan + if az.CloudProviderBackoff && shouldRetryAPIRequest(resp.Response, err) { glog.V(2).Infof("create(%s) backing off: vm(%s)", az.ResourceGroup, vmName) retryErr := az.CreateOrUpdateVMWithRetry(vmName, newVM) if retryErr != nil { diff --git a/pkg/cloudprovider/providers/azure/azure_test.go b/pkg/cloudprovider/providers/azure/azure_test.go index 1c86f2e1a78c..08d74b023d34 100644 --- a/pkg/cloudprovider/providers/azure/azure_test.go +++ b/pkg/cloudprovider/providers/azure/azure_test.go @@ -556,7 +556,7 @@ func TestProtocolTranslationTCP(t *testing.T) { if *transportProto != network.TransportProtocolTCP { t.Errorf("Expected TCP LoadBalancer Rule Protocol. Got %v", transportProto) } - if *securityGroupProto != network.TCP { + if *securityGroupProto != network.SecurityRuleProtocolTCP { t.Errorf("Expected TCP SecurityGroup Protocol. Got %v", transportProto) } if *probeProto != network.ProbeProtocolTCP { @@ -570,7 +570,7 @@ func TestProtocolTranslationUDP(t *testing.T) { if *transportProto != network.TransportProtocolUDP { t.Errorf("Expected UDP LoadBalancer Rule Protocol. Got %v", transportProto) } - if *securityGroupProto != network.UDP { + if *securityGroupProto != network.SecurityRuleProtocolUDP { t.Errorf("Expected UDP SecurityGroup Protocol. Got %v", transportProto) } if probeProto != nil { diff --git a/pkg/cloudprovider/providers/azure/azure_util.go b/pkg/cloudprovider/providers/azure/azure_util.go index d8d5b113defd..0b9c44c04734 100644 --- a/pkg/cloudprovider/providers/azure/azure_util.go +++ b/pkg/cloudprovider/providers/azure/azure_util.go @@ -135,12 +135,12 @@ func getProtocolsFromKubernetesProtocol(protocol v1.Protocol) (*network.Transpor switch protocol { case v1.ProtocolTCP: transportProto = network.TransportProtocolTCP - securityProto = network.TCP + securityProto = network.SecurityRuleProtocolTCP probeProto = network.ProbeProtocolTCP return &transportProto, &securityProto, &probeProto, nil case v1.ProtocolUDP: transportProto = network.TransportProtocolUDP - securityProto = network.UDP + securityProto = network.SecurityRuleProtocolUDP return &transportProto, &securityProto, nil, nil default: return &transportProto, &securityProto, &probeProto, fmt.Errorf("Only TCP and UDP are supported for Azure LoadBalancers") diff --git a/pkg/credentialprovider/azure/BUILD b/pkg/credentialprovider/azure/BUILD index 41b2154ad536..4f52afc4d366 100644 --- a/pkg/credentialprovider/azure/BUILD +++ b/pkg/credentialprovider/azure/BUILD @@ -16,6 +16,8 @@ go_library( "//pkg/cloudprovider/providers/azure:go_default_library", "//pkg/credentialprovider:go_default_library", "//vendor/github.com/Azure/azure-sdk-for-go/arm/containerregistry:go_default_library", + "//vendor/github.com/Azure/go-autorest/autorest:go_default_library", + "//vendor/github.com/Azure/go-autorest/autorest/adal:go_default_library", "//vendor/github.com/Azure/go-autorest/autorest/azure:go_default_library", "//vendor/github.com/golang/glog:go_default_library", "//vendor/github.com/spf13/pflag:go_default_library", diff --git a/pkg/credentialprovider/azure/azure_credentials.go b/pkg/credentialprovider/azure/azure_credentials.go index 771c41780b53..bdf618b96d33 100644 --- a/pkg/credentialprovider/azure/azure_credentials.go +++ b/pkg/credentialprovider/azure/azure_credentials.go @@ -23,6 +23,8 @@ import ( yaml "gopkg.in/yaml.v2" "github.com/Azure/azure-sdk-for-go/arm/containerregistry" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/adal" azureapi "github.com/Azure/go-autorest/autorest/azure" "github.com/golang/glog" "github.com/spf13/pflag" @@ -94,13 +96,13 @@ func (a *acrProvider) Enabled() bool { return false } - oauthConfig, err := a.environment.OAuthConfigForTenant(a.config.TenantID) + oauthConfig, err := adal.NewOAuthConfig(a.environment.ActiveDirectoryEndpoint, a.config.TenantID) if err != nil { glog.Errorf("Failed to get oauth config: %v", err) return false } - servicePrincipalToken, err := azureapi.NewServicePrincipalToken( + servicePrincipalToken, err := adal.NewServicePrincipalToken( *oauthConfig, a.config.AADClientID, a.config.AADClientSecret, @@ -112,7 +114,7 @@ func (a *acrProvider) Enabled() bool { registryClient := containerregistry.NewRegistriesClient(a.config.SubscriptionID) registryClient.BaseURI = a.environment.ResourceManagerEndpoint - registryClient.Authorizer = servicePrincipalToken + registryClient.Authorizer = autorest.NewBearerAuthorizer(servicePrincipalToken) a.registryClient = registryClient return true diff --git a/staging/src/k8s.io/client-go/Godeps/Godeps.json b/staging/src/k8s.io/client-go/Godeps/Godeps.json index d925a58fb88d..cb5965d63f91 100644 --- a/staging/src/k8s.io/client-go/Godeps/Godeps.json +++ b/staging/src/k8s.io/client-go/Godeps/Godeps.json @@ -16,15 +16,19 @@ }, { "ImportPath": "github.com/Azure/go-autorest/autorest", - "Rev": "d7c034a8af24eda120dd6460bfcd6d9ed14e43ca" + "Rev": "58f6f26e200fa5dfb40c9cd1c83f3e2c860d779d" + }, + { + "ImportPath": "github.com/Azure/go-autorest/autorest/adal", + "Rev": "58f6f26e200fa5dfb40c9cd1c83f3e2c860d779d" }, { "ImportPath": "github.com/Azure/go-autorest/autorest/azure", - "Rev": "d7c034a8af24eda120dd6460bfcd6d9ed14e43ca" + "Rev": "58f6f26e200fa5dfb40c9cd1c83f3e2c860d779d" }, { "ImportPath": "github.com/Azure/go-autorest/autorest/date", - "Rev": "d7c034a8af24eda120dd6460bfcd6d9ed14e43ca" + "Rev": "58f6f26e200fa5dfb40c9cd1c83f3e2c860d779d" }, { "ImportPath": "github.com/PuerkitoBio/purell", diff --git a/staging/src/k8s.io/client-go/plugin/pkg/client/auth/azure/BUILD b/staging/src/k8s.io/client-go/plugin/pkg/client/auth/azure/BUILD index 0c8f30954962..00c96d666d35 100644 --- a/staging/src/k8s.io/client-go/plugin/pkg/client/auth/azure/BUILD +++ b/staging/src/k8s.io/client-go/plugin/pkg/client/auth/azure/BUILD @@ -13,7 +13,7 @@ go_test( srcs = ["azure_test.go"], library = ":go_default_library", tags = ["automanaged"], - deps = ["//vendor/github.com/Azure/go-autorest/autorest/azure:go_default_library"], + deps = ["//vendor/github.com/Azure/go-autorest/autorest/adal:go_default_library"], ) go_library( @@ -22,6 +22,7 @@ go_library( tags = ["automanaged"], deps = [ "//vendor/github.com/Azure/go-autorest/autorest:go_default_library", + "//vendor/github.com/Azure/go-autorest/autorest/adal:go_default_library", "//vendor/github.com/Azure/go-autorest/autorest/azure:go_default_library", "//vendor/github.com/golang/glog:go_default_library", "//vendor/k8s.io/client-go/rest:go_default_library", diff --git a/staging/src/k8s.io/client-go/plugin/pkg/client/auth/azure/azure.go b/staging/src/k8s.io/client-go/plugin/pkg/client/auth/azure/azure.go index 342fbb78f572..06744e742445 100644 --- a/staging/src/k8s.io/client-go/plugin/pkg/client/auth/azure/azure.go +++ b/staging/src/k8s.io/client-go/plugin/pkg/client/auth/azure/azure.go @@ -24,6 +24,7 @@ import ( "sync" "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/adal" "github.com/Azure/go-autorest/autorest/azure" "github.com/golang/glog" @@ -137,7 +138,7 @@ func (r *azureRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) } type azureToken struct { - token azure.Token + token adal.Token clientID string tenantID string apiserverID string @@ -234,7 +235,7 @@ func (ts *azureTokenSource) retrieveTokenFromCfg() (*azureToken, error) { } return &azureToken{ - token: azure.Token{ + token: adal.Token{ AccessToken: accessToken, RefreshToken: refreshToken, ExpiresIn: expiresIn, @@ -268,15 +269,15 @@ func (ts *azureTokenSource) storeTokenInCfg(token *azureToken) error { } func (ts *azureTokenSource) refreshToken(token *azureToken) (*azureToken, error) { - oauthConfig, err := azure.PublicCloud.OAuthConfigForTenant(token.tenantID) + oauthConfig, err := adal.NewOAuthConfig(azure.PublicCloud.ActiveDirectoryEndpoint, token.tenantID) if err != nil { return nil, fmt.Errorf("building the OAuth configuration for token refresh: %v", err) } - callback := func(t azure.Token) error { + callback := func(t adal.Token) error { return nil } - spt, err := azure.NewServicePrincipalTokenFromManualToken( + spt, err := adal.NewServicePrincipalTokenFromManualToken( *oauthConfig, token.clientID, token.apiserverID, @@ -324,12 +325,12 @@ func newAzureTokenSourceDeviceCode(environment azure.Environment, clientID strin } func (ts *azureTokenSourceDeviceCode) Token() (*azureToken, error) { - oauthConfig, err := ts.environment.OAuthConfigForTenant(ts.tenantID) + oauthConfig, err := adal.NewOAuthConfig(ts.environment.ActiveDirectoryEndpoint, ts.tenantID) if err != nil { return nil, fmt.Errorf("building the OAuth configuration for device code authentication: %v", err) } client := &autorest.Client{} - deviceCode, err := azure.InitiateDeviceAuth(client, *oauthConfig, ts.clientID, ts.apiserverID) + deviceCode, err := adal.InitiateDeviceAuth(client, *oauthConfig, ts.clientID, ts.apiserverID) if err != nil { return nil, fmt.Errorf("initialing the device code authentication: %v", err) } @@ -339,7 +340,7 @@ func (ts *azureTokenSourceDeviceCode) Token() (*azureToken, error) { return nil, fmt.Errorf("prompting the device code message: %v", err) } - token, err := azure.WaitForUserCompletion(client, deviceCode) + token, err := adal.WaitForUserCompletion(client, deviceCode) if err != nil { return nil, fmt.Errorf("waiting for device code authentication to complete: %v", err) } diff --git a/staging/src/k8s.io/client-go/plugin/pkg/client/auth/azure/azure_test.go b/staging/src/k8s.io/client-go/plugin/pkg/client/auth/azure/azure_test.go index 78d28b6e2fc0..b420712bc122 100644 --- a/staging/src/k8s.io/client-go/plugin/pkg/client/auth/azure/azure_test.go +++ b/staging/src/k8s.io/client-go/plugin/pkg/client/auth/azure/azure_test.go @@ -23,7 +23,7 @@ import ( "testing" "time" - "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/adal" ) func TestAzureTokenSource(t *testing.T) { @@ -120,8 +120,8 @@ func token2Cfg(token *azureToken) map[string]string { return cfg } -func newFackeAzureToken(accessToken string, expiresOn string) azure.Token { - return azure.Token{ +func newFackeAzureToken(accessToken string, expiresOn string) adal.Token { + return adal.Token{ AccessToken: accessToken, RefreshToken: "fake", ExpiresIn: "3600", diff --git a/vendor/BUILD b/vendor/BUILD index ce3253bb2aed..adaeeec05b90 100644 --- a/vendor/BUILD +++ b/vendor/BUILD @@ -288,6 +288,7 @@ filegroup( "//vendor/github.com/robfig/cron:all-srcs", "//vendor/github.com/rubiojr/go-vhd/vhd:all-srcs", "//vendor/github.com/russross/blackfriday:all-srcs", + "//vendor/github.com/satori/uuid:all-srcs", "//vendor/github.com/seccomp/libseccomp-golang:all-srcs", "//vendor/github.com/shurcooL/sanitized_anchor_name:all-srcs", "//vendor/github.com/spf13/afero:all-srcs", diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/BUILD b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/BUILD index 7ecb69c33c57..e2d8fa57d93c 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/BUILD +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/BUILD @@ -12,8 +12,9 @@ go_library( srcs = [ "availabilitysets.go", "client.go", + "images.go", "models.go", - "usageoperations.go", + "usage.go", "version.go", "virtualmachineextensionimages.go", "virtualmachineextensions.go", 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 old mode 100644 new mode 100755 index 34a4d2df8269..738c2c61ea0f --- 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,14 +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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" "net/http" ) @@ -44,26 +43,21 @@ func NewAvailabilitySetsClientWithBaseURI(baseURI string, subscriptionID string) // CreateOrUpdate create or update an availability set. // -// resourceGroupName is the name of the resource group. name is the name of -// the availability set. parameters is parameters supplied to the Create +// resourceGroupName is the name of the resource group. name is the name of the +// availability set. parameters is parameters supplied to the Create // Availability Set operation. func (client AvailabilitySetsClient) CreateOrUpdate(resourceGroupName string, name string, parameters AvailabilitySet) (result AvailabilitySet, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.AvailabilitySetProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.AvailabilitySetProperties.Statuses", Name: validation.ReadOnly, Rule: true, Chain: nil}}}}}}); err != nil { - return result, validation.NewErrorWithValidationError(err, "compute.AvailabilitySetsClient", "CreateOrUpdate") - } - req, err := client.CreateOrUpdatePreparer(resourceGroupName, name, parameters) if err != nil { - return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "CreateOrUpdate", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "CreateOrUpdate", nil, "Failure preparing request") + return } resp, err := client.CreateOrUpdateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "CreateOrUpdate", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "CreateOrUpdate", resp, "Failure sending request") + return } result, err = client.CreateOrUpdateResponder(resp) @@ -82,8 +76,9 @@ func (client AvailabilitySetsClient) CreateOrUpdatePreparer(resourceGroupName st "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -119,16 +114,18 @@ 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, err error) { +func (client AvailabilitySetsClient) Delete(resourceGroupName string, availabilitySetName string) (result OperationStatusResponse, err error) { req, err := client.DeletePreparer(resourceGroupName, availabilitySetName) if err != nil { - return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Delete", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Delete", nil, "Failure preparing request") + return } resp, err := client.DeleteSender(req) if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Delete", resp, "Failure sending request") + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Delete", resp, "Failure sending request") + return } result, err = client.DeleteResponder(resp) @@ -147,8 +144,9 @@ func (client AvailabilitySetsClient) DeletePreparer(resourceGroupName string, av "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -167,13 +165,14 @@ func (client AvailabilitySetsClient) DeleteSender(req *http.Request) (*http.Resp // DeleteResponder handles the response to the Delete request. The method always // closes the http.Response Body. -func (client AvailabilitySetsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { +func (client AvailabilitySetsClient) DeleteResponder(resp *http.Response) (result OperationStatusResponse, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } @@ -184,13 +183,15 @@ func (client AvailabilitySetsClient) DeleteResponder(resp *http.Response) (resul 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Get", nil, "Failure preparing request") + return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Get", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Get", resp, "Failure sending request") + return } result, err = client.GetResponder(resp) @@ -209,8 +210,9 @@ func (client AvailabilitySetsClient) GetPreparer(resourceGroupName string, avail "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -246,13 +248,15 @@ func (client AvailabilitySetsClient) GetResponder(resp *http.Response) (result A 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "List", nil, "Failure preparing request") + return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "List", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "List", resp, "Failure sending request") + return } result, err = client.ListResponder(resp) @@ -270,8 +274,9 @@ func (client AvailabilitySetsClient) ListPreparer(resourceGroupName string) (*ht "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -309,13 +314,15 @@ func (client AvailabilitySetsClient) ListResponder(resp *http.Response) (result 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "ListAvailableSizes", nil, "Failure preparing request") + return } resp, err := client.ListAvailableSizesSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "ListAvailableSizes", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "ListAvailableSizes", resp, "Failure sending request") + return } result, err = client.ListAvailableSizesResponder(resp) @@ -334,8 +341,9 @@ func (client AvailabilitySetsClient) ListAvailableSizesPreparer(resourceGroupNam "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( 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 old mode 100644 new mode 100755 index e8f3fb3e6d3d..c60452b9d794 --- 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,5 +1,5 @@ // Package compute implements the Azure ARM Compute service API version -// 2016-03-30. +// 2016-04-30-preview. // // The Compute Management Client. package compute @@ -18,7 +18,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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -27,9 +27,6 @@ import ( ) const ( - // APIVersion is the version of the Compute - APIVersion = "2016-03-30" - // DefaultBaseURI is the default URI used for the service Compute DefaultBaseURI = "https://management.azure.com" ) @@ -38,7 +35,6 @@ const ( type ManagementClient struct { autorest.Client BaseURI string - APIVersion string SubscriptionID string } @@ -52,7 +48,6 @@ func NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient { return ManagementClient{ Client: autorest.NewClientWithUserAgent(UserAgent()), BaseURI: baseURI, - APIVersion: APIVersion, SubscriptionID: subscriptionID, } } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/images.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/images.go new file mode 100755 index 000000000000..64f14dd082ff --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/images.go @@ -0,0 +1,463 @@ +package compute + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// ImagesClient is the the Compute Management Client. +type ImagesClient struct { + ManagementClient +} + +// NewImagesClient creates an instance of the ImagesClient client. +func NewImagesClient(subscriptionID string) ImagesClient { + return NewImagesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewImagesClientWithBaseURI creates an instance of the ImagesClient client. +func NewImagesClientWithBaseURI(baseURI string, subscriptionID string) ImagesClient { + return ImagesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create or update an image. 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. imageName is the name +// of the image. parameters is parameters supplied to the Create Image +// operation. +func (client ImagesClient) CreateOrUpdate(resourceGroupName string, imageName string, parameters Image, cancel <-chan struct{}) (<-chan Image, <-chan error) { + resultChan := make(chan Image, 1) + errChan := make(chan error, 1) + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.ImageProperties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.ImageProperties.StorageProfile", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.ImageProperties.StorageProfile.OsDisk", Name: validation.Null, Rule: true, Chain: nil}}}, + }}}}}); err != nil { + errChan <- validation.NewErrorWithValidationError(err, "compute.ImagesClient", "CreateOrUpdate") + close(errChan) + close(resultChan) + return resultChan, errChan + } + + go func() { + var err error + var result Image + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.CreateOrUpdatePreparer(resourceGroupName, imageName, parameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.ImagesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.ImagesClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.ImagesClient", "CreateOrUpdate", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client ImagesClient) CreateOrUpdatePreparer(resourceGroupName string, imageName string, parameters Image, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "imageName": autorest.Encode("path", imageName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-04-30-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/images/{imageName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client ImagesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + 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 ImagesClient) CreateOrUpdateResponder(resp *http.Response) (result Image, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes an Image. 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. imageName is the name +// of the image. +func (client ImagesClient) Delete(resourceGroupName string, imageName string, cancel <-chan struct{}) (<-chan OperationStatusResponse, <-chan error) { + resultChan := make(chan OperationStatusResponse, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result OperationStatusResponse + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeletePreparer(resourceGroupName, imageName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.ImagesClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.ImagesClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.ImagesClient", "Delete", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// DeletePreparer prepares the Delete request. +func (client ImagesClient) DeletePreparer(resourceGroupName string, imageName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "imageName": autorest.Encode("path", imageName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-04-30-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/images/{imageName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client ImagesClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client ImagesClient) DeleteResponder(resp *http.Response) (result OperationStatusResponse, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Get gets an image. +// +// resourceGroupName is the name of the resource group. imageName is the name +// of the image. expand is the expand expression to apply on the operation. +func (client ImagesClient) Get(resourceGroupName string, imageName string, expand string) (result Image, err error) { + req, err := client.GetPreparer(resourceGroupName, imageName, expand) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.ImagesClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.ImagesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.ImagesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client ImagesClient) GetPreparer(resourceGroupName string, imageName string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "imageName": autorest.Encode("path", imageName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-04-30-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/images/{imageName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client ImagesClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client ImagesClient) GetResponder(resp *http.Response) (result Image, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List gets the list of Images in the subscription. Use nextLink property in +// the response to get the next page of Images. Do this till nextLink is not +// null to fetch all the Images. +func (client ImagesClient) List() (result ImageListResult, err error) { + req, err := client.ListPreparer() + if err != nil { + err = autorest.NewErrorWithError(err, "compute.ImagesClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.ImagesClient", "List", resp, "Failure sending request") + return + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.ImagesClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client ImagesClient) ListPreparer() (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-04-30-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/images", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client ImagesClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client ImagesClient) ListResponder(resp *http.Response) (result ImageListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListNextResults retrieves the next set of results, if any. +func (client ImagesClient) ListNextResults(lastResults ImageListResult) (result ImageListResult, err error) { + req, err := lastResults.ImageListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.ImagesClient", "List", nil, "Failure preparing next results request") + } + if req == nil { + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.ImagesClient", "List", resp, "Failure sending next results request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.ImagesClient", "List", resp, "Failure responding to next results request") + } + + return +} + +// ListByResourceGroup gets the list of images under a resource group. +// +// resourceGroupName is the name of the resource group. +func (client ImagesClient) ListByResourceGroup(resourceGroupName string) (result ImageListResult, err error) { + req, err := client.ListByResourceGroupPreparer(resourceGroupName) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.ImagesClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.ImagesClient", "ListByResourceGroup", resp, "Failure sending request") + return + } + + result, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.ImagesClient", "ListByResourceGroup", resp, "Failure responding to request") + } + + return +} + +// ListByResourceGroupPreparer prepares the ListByResourceGroup request. +func (client ImagesClient) ListByResourceGroupPreparer(resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-04-30-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/images", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the +// http.Response Body if it receives an error. +func (client ImagesClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always +// closes the http.Response Body. +func (client ImagesClient) ListByResourceGroupResponder(resp *http.Response) (result ImageListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByResourceGroupNextResults retrieves the next set of results, if any. +func (client ImagesClient) ListByResourceGroupNextResults(lastResults ImageListResult) (result ImageListResult, err error) { + req, err := lastResults.ImageListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "compute.ImagesClient", "ListByResourceGroup", nil, "Failure preparing next results request") + } + if req == nil { + return + } + + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "compute.ImagesClient", "ListByResourceGroup", resp, "Failure sending next results request") + } + + result, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.ImagesClient", "ListByResourceGroup", resp, "Failure responding to next results request") + } + + return +} 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 old mode 100644 new mode 100755 index 13dbe637c4a0..a9524daeffac --- 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,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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -66,6 +66,19 @@ const ( InstanceView InstanceViewTypes = "instanceView" ) +// OperatingSystemStateTypes enumerates the values for operating system state +// types. +type OperatingSystemStateTypes string + +const ( + // Generalized specifies the generalized state for operating system state + // types. + Generalized OperatingSystemStateTypes = "Generalized" + // Specialized specifies the specialized state for operating system state + // types. + Specialized OperatingSystemStateTypes = "Specialized" +) + // OperatingSystemTypes enumerates the values for operating system types. type OperatingSystemTypes string @@ -94,6 +107,15 @@ const ( HTTPS ProtocolTypes = "Https" ) +// ResourceIdentityType enumerates the values for resource identity type. +type ResourceIdentityType string + +const ( + // SystemAssigned specifies the system assigned state for resource identity + // type. + SystemAssigned ResourceIdentityType = "SystemAssigned" +) + // SettingNames enumerates the values for setting names. type SettingNames string @@ -117,6 +139,16 @@ const ( Warning StatusLevelTypes = "Warning" ) +// StorageAccountTypes enumerates the values for storage account types. +type StorageAccountTypes string + +const ( + // PremiumLRS specifies the premium lrs state for storage account types. + PremiumLRS StorageAccountTypes = "Premium_LRS" + // StandardLRS specifies the standard lrs state for storage account types. + StandardLRS StorageAccountTypes = "Standard_LRS" +) + // UpgradeMode enumerates the values for upgrade mode. type UpgradeMode string @@ -127,8 +159,8 @@ const ( Manual UpgradeMode = "Manual" ) -// VirtualMachineScaleSetSkuScaleType enumerates the values for virtual -// machine scale set sku scale type. +// VirtualMachineScaleSetSkuScaleType enumerates the values for virtual machine +// scale set sku scale type. type VirtualMachineScaleSetSkuScaleType string const ( @@ -335,8 +367,8 @@ const ( // AdditionalUnattendContent is additional XML formatted information that can // be included in the Unattend.xml file, which is used by Windows Setup. -// Contents are defined by setting name, component name, and the pass in -// which the content is a applied. +// Contents are defined by setting name, component name, and the pass in which +// the content is a applied. type AdditionalUnattendContent struct { PassName PassNames `json:"passName,omitempty"` ComponentName ComponentNames `json:"componentName,omitempty"` @@ -374,6 +406,7 @@ type AvailabilitySet struct { Location *string `json:"location,omitempty"` Tags *map[string]*string `json:"tags,omitempty"` *AvailabilitySetProperties `json:"properties,omitempty"` + Sku *Sku `json:"sku,omitempty"` } // AvailabilitySetListResult is the List Availability Set operation response. @@ -388,6 +421,7 @@ type AvailabilitySetProperties struct { PlatformFaultDomainCount *int32 `json:"platformFaultDomainCount,omitempty"` VirtualMachines *[]SubResource `json:"virtualMachines,omitempty"` Statuses *[]InstanceViewStatus `json:"statuses,omitempty"` + Managed *bool `json:"managed,omitempty"` } // BootDiagnostics is describes Boot Diagnostics. @@ -405,13 +439,14 @@ type BootDiagnosticsInstanceView struct { // DataDisk is describes a data disk. type DataDisk struct { - 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 *int32 `json:"diskSizeGB,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 *int32 `json:"diskSizeGB,omitempty"` + ManagedDisk *ManagedDiskParameters `json:"managedDisk,omitempty"` } // DataDiskImage is contains the data disk images information. @@ -442,14 +477,79 @@ type HardwareProfile struct { VMSize VirtualMachineSizeTypes `json:"vmSize,omitempty"` } +// Image is describes an Image. +type Image 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"` + *ImageProperties `json:"properties,omitempty"` +} + +// ImageDataDisk is describes a data disk. +type ImageDataDisk struct { + Lun *int32 `json:"lun,omitempty"` + Snapshot *SubResource `json:"snapshot,omitempty"` + ManagedDisk *SubResource `json:"managedDisk,omitempty"` + BlobURI *string `json:"blobUri,omitempty"` + Caching CachingTypes `json:"caching,omitempty"` + DiskSizeGB *int32 `json:"diskSizeGB,omitempty"` +} + +// ImageListResult is the List Image operation response. +type ImageListResult struct { + autorest.Response `json:"-"` + Value *[]Image `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// ImageListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client ImageListResult) ImageListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// ImageOSDisk is describes an Operating System disk. +type ImageOSDisk struct { + OsType OperatingSystemTypes `json:"osType,omitempty"` + OsState OperatingSystemStateTypes `json:"osState,omitempty"` + Snapshot *SubResource `json:"snapshot,omitempty"` + ManagedDisk *SubResource `json:"managedDisk,omitempty"` + BlobURI *string `json:"blobUri,omitempty"` + Caching CachingTypes `json:"caching,omitempty"` + DiskSizeGB *int32 `json:"diskSizeGB,omitempty"` +} + +// ImageProperties is describes the properties of an Image. +type ImageProperties struct { + SourceVirtualMachine *SubResource `json:"sourceVirtualMachine,omitempty"` + StorageProfile *ImageStorageProfile `json:"storageProfile,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + // ImageReference is the image reference. type ImageReference struct { + ID *string `json:"id,omitempty"` Publisher *string `json:"publisher,omitempty"` Offer *string `json:"offer,omitempty"` Sku *string `json:"sku,omitempty"` Version *string `json:"version,omitempty"` } +// ImageStorageProfile is describes a storage profile. +type ImageStorageProfile struct { + OsDisk *ImageOSDisk `json:"osDisk,omitempty"` + DataDisks *[]ImageDataDisk `json:"dataDisks,omitempty"` +} + // InnerError is inner error details. type InnerError struct { Exceptiontype *string `json:"exceptiontype,omitempty"` @@ -520,6 +620,12 @@ type LongRunningOperationProperties struct { Output *map[string]interface{} `json:"output,omitempty"` } +// ManagedDiskParameters is the parameters of a managed disk. +type ManagedDiskParameters struct { + ID *string `json:"id,omitempty"` + StorageAccountType StorageAccountTypes `json:"storageAccountType,omitempty"` +} + // NetworkInterfaceReference is describes a network interface reference. type NetworkInterfaceReference struct { ID *string `json:"id,omitempty"` @@ -537,6 +643,16 @@ type NetworkProfile struct { NetworkInterfaces *[]NetworkInterfaceReference `json:"networkInterfaces,omitempty"` } +// OperationStatusResponse is operation status response +type OperationStatusResponse struct { + autorest.Response `json:"-"` + Name *string `json:"name,omitempty"` + Status *string `json:"status,omitempty"` + StartTime *date.Time `json:"startTime,omitempty"` + EndTime *date.Time `json:"endTime,omitempty"` + Error *APIError `json:"error,omitempty"` +} + // OSDisk is describes an Operating System disk. type OSDisk struct { OsType OperatingSystemTypes `json:"osType,omitempty"` @@ -547,6 +663,7 @@ type OSDisk struct { Caching CachingTypes `json:"caching,omitempty"` CreateOption DiskCreateOptionTypes `json:"createOption,omitempty"` DiskSizeGB *int32 `json:"diskSizeGB,omitempty"` + ManagedDisk *ManagedDiskParameters `json:"managedDisk,omitempty"` } // OSDiskImage is contains the os disk image information. @@ -581,7 +698,7 @@ type PurchasePlan struct { Product *string `json:"product,omitempty"` } -// Resource is the resource model definition. +// Resource is the Resource model definition. type Resource struct { ID *string `json:"id,omitempty"` Name *string `json:"name,omitempty"` @@ -621,6 +738,11 @@ type SubResource struct { ID *string `json:"id,omitempty"` } +// SubResourceReadOnly is +type SubResourceReadOnly struct { + ID *string `json:"id,omitempty"` +} + // UpgradePolicy is describes an upgrade policy - automatic or manual. type UpgradePolicy struct { Mode UpgradeMode `json:"mode,omitempty"` @@ -640,8 +762,8 @@ type UsageName struct { LocalizedValue *string `json:"localizedValue,omitempty"` } -// VaultCertificate is describes a single certificate reference in a Key -// Vault, and where the certificate should reside on the VM. +// VaultCertificate is describes a single certificate reference in a Key Vault, +// and where the certificate should reside on the VM. type VaultCertificate struct { CertificateURL *string `json:"certificateUrl,omitempty"` CertificateStore *string `json:"certificateStore,omitempty"` @@ -670,10 +792,11 @@ type VirtualMachine struct { Plan *Plan `json:"plan,omitempty"` *VirtualMachineProperties `json:"properties,omitempty"` Resources *[]VirtualMachineExtension `json:"resources,omitempty"` + Identity *VirtualMachineIdentity `json:"identity,omitempty"` } -// VirtualMachineAgentInstanceView is the instance view of the VM Agent -// running on the virtual machine. +// VirtualMachineAgentInstanceView is the instance view of the VM Agent running +// on the virtual machine. type VirtualMachineAgentInstanceView struct { VMAgentVersion *string `json:"vmAgentVersion,omitempty"` ExtensionHandlers *[]VirtualMachineExtensionHandlerInstanceView `json:"extensionHandlers,omitempty"` @@ -711,8 +834,8 @@ type VirtualMachineExtension struct { *VirtualMachineExtensionProperties `json:"properties,omitempty"` } -// VirtualMachineExtensionHandlerInstanceView is the instance view of a -// virtual machine extension handler. +// VirtualMachineExtensionHandlerInstanceView is the instance view of a virtual +// machine extension handler. type VirtualMachineExtensionHandlerInstanceView struct { Type *string `json:"type,omitempty"` TypeHandlerVersion *string `json:"typeHandlerVersion,omitempty"` @@ -764,6 +887,13 @@ type VirtualMachineExtensionProperties struct { InstanceView *VirtualMachineExtensionInstanceView `json:"instanceView,omitempty"` } +// VirtualMachineIdentity is identity for the virtual machine. +type VirtualMachineIdentity struct { + PrincipalID *string `json:"principalId,omitempty"` + TenantID *string `json:"tenantId,omitempty"` + Type ResourceIdentityType `json:"type,omitempty"` +} + // VirtualMachineImage is describes a Virtual Machine Image. type VirtualMachineImage struct { autorest.Response `json:"-"` @@ -844,7 +974,20 @@ type VirtualMachineScaleSet struct { Location *string `json:"location,omitempty"` Tags *map[string]*string `json:"tags,omitempty"` Sku *Sku `json:"sku,omitempty"` + Plan *Plan `json:"plan,omitempty"` *VirtualMachineScaleSetProperties `json:"properties,omitempty"` + Identity *VirtualMachineScaleSetIdentity `json:"identity,omitempty"` +} + +// VirtualMachineScaleSetDataDisk is describes a virtual machine scale set data +// disk. +type VirtualMachineScaleSetDataDisk struct { + Name *string `json:"name,omitempty"` + Lun *int32 `json:"lun,omitempty"` + Caching CachingTypes `json:"caching,omitempty"` + CreateOption DiskCreateOptionTypes `json:"createOption,omitempty"` + DiskSizeGB *int32 `json:"diskSizeGB,omitempty"` + ManagedDisk *VirtualMachineScaleSetManagedDiskParameters `json:"managedDisk,omitempty"` } // VirtualMachineScaleSetExtension is describes a Virtual Machine Scale Set @@ -873,8 +1016,16 @@ type VirtualMachineScaleSetExtensionProperties struct { ProvisioningState *string `json:"provisioningState,omitempty"` } -// VirtualMachineScaleSetInstanceView is the instance view of a virtual -// machine scale set. +// VirtualMachineScaleSetIdentity is identity for the virtual machine scale +// set. +type VirtualMachineScaleSetIdentity struct { + PrincipalID *string `json:"principalId,omitempty"` + TenantID *string `json:"tenantId,omitempty"` + Type ResourceIdentityType `json:"type,omitempty"` +} + +// VirtualMachineScaleSetInstanceView is the instance view of a virtual machine +// scale set. type VirtualMachineScaleSetInstanceView struct { autorest.Response `json:"-"` VirtualMachine *VirtualMachineScaleSetInstanceViewStatusesSummary `json:"virtualMachine,omitempty"` @@ -965,6 +1116,12 @@ func (client VirtualMachineScaleSetListWithLinkResult) VirtualMachineScaleSetLis autorest.WithBaseURL(to.String(client.NextLink))) } +// VirtualMachineScaleSetManagedDiskParameters is describes the parameters of a +// ScaleSet managed disk. +type VirtualMachineScaleSetManagedDiskParameters struct { + StorageAccountType StorageAccountTypes `json:"storageAccountType,omitempty"` +} + // VirtualMachineScaleSetNetworkConfiguration is describes a virtual machine // scale set network profile's network configurations. type VirtualMachineScaleSetNetworkConfiguration struct { @@ -989,12 +1146,13 @@ type VirtualMachineScaleSetNetworkProfile struct { // VirtualMachineScaleSetOSDisk is describes a virtual machine scale set // operating system disk. type VirtualMachineScaleSetOSDisk struct { - Name *string `json:"name,omitempty"` - Caching CachingTypes `json:"caching,omitempty"` - CreateOption DiskCreateOptionTypes `json:"createOption,omitempty"` - OsType OperatingSystemTypes `json:"osType,omitempty"` - Image *VirtualHardDisk `json:"image,omitempty"` - VhdContainers *[]string `json:"vhdContainers,omitempty"` + Name *string `json:"name,omitempty"` + Caching CachingTypes `json:"caching,omitempty"` + CreateOption DiskCreateOptionTypes `json:"createOption,omitempty"` + OsType OperatingSystemTypes `json:"osType,omitempty"` + Image *VirtualHardDisk `json:"image,omitempty"` + VhdContainers *[]string `json:"vhdContainers,omitempty"` + ManagedDisk *VirtualMachineScaleSetManagedDiskParameters `json:"managedDisk,omitempty"` } // VirtualMachineScaleSetOSProfile is describes a virtual machine scale set OS @@ -1016,6 +1174,7 @@ type VirtualMachineScaleSetProperties struct { VirtualMachineProfile *VirtualMachineScaleSetVMProfile `json:"virtualMachineProfile,omitempty"` ProvisioningState *string `json:"provisioningState,omitempty"` Overprovision *bool `json:"overprovision,omitempty"` + SinglePlacementGroup *bool `json:"singlePlacementGroup,omitempty"` } // VirtualMachineScaleSetSku is describes an available virtual machine scale @@ -1037,8 +1196,9 @@ type VirtualMachineScaleSetSkuCapacity struct { // VirtualMachineScaleSetStorageProfile is describes a virtual machine scale // set storage profile. type VirtualMachineScaleSetStorageProfile struct { - ImageReference *ImageReference `json:"imageReference,omitempty"` - OsDisk *VirtualMachineScaleSetOSDisk `json:"osDisk,omitempty"` + ImageReference *ImageReference `json:"imageReference,omitempty"` + OsDisk *VirtualMachineScaleSetOSDisk `json:"osDisk,omitempty"` + DataDisks *[]VirtualMachineScaleSetDataDisk `json:"dataDisks,omitempty"` } // VirtualMachineScaleSetVM is describes a virtual machine scale set virtual @@ -1088,10 +1248,11 @@ type VirtualMachineScaleSetVMInstanceView struct { Extensions *[]VirtualMachineExtensionInstanceView `json:"extensions,omitempty"` BootDiagnostics *BootDiagnosticsInstanceView `json:"bootDiagnostics,omitempty"` Statuses *[]InstanceViewStatus `json:"statuses,omitempty"` + PlacementGroupID *string `json:"placementGroupId,omitempty"` } -// VirtualMachineScaleSetVMListResult is the List Virtual Machine Scale Set -// VMs operation response. +// VirtualMachineScaleSetVMListResult is the List Virtual Machine Scale Set VMs +// operation response. type VirtualMachineScaleSetVMListResult struct { autorest.Response `json:"-"` Value *[]VirtualMachineScaleSetVM `json:"value,omitempty"` @@ -1123,6 +1284,7 @@ type VirtualMachineScaleSetVMProfile struct { // machine scale set virtual machine. type VirtualMachineScaleSetVMProperties struct { LatestModelApplied *bool `json:"latestModelApplied,omitempty"` + VMID *string `json:"vmId,omitempty"` InstanceView *VirtualMachineInstanceView `json:"instanceView,omitempty"` HardwareProfile *HardwareProfile `json:"hardwareProfile,omitempty"` StorageProfile *StorageProfile `json:"storageProfile,omitempty"` 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/usage.go old mode 100644 new mode 100755 similarity index 60% rename from vendor/github.com/Azure/azure-sdk-for-go/arm/compute/usageoperations.go rename to vendor/github.com/Azure/azure-sdk-for-go/arm/compute/usage.go index 5fb5bd6f555e..97c53e0efd7f --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/usageoperations.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/compute/usage.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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -25,21 +25,19 @@ import ( "net/http" ) -// UsageOperationsClient is the the Compute Management Client. -type UsageOperationsClient struct { +// UsageClient is the the Compute Management Client. +type UsageClient struct { ManagementClient } -// NewUsageOperationsClient creates an instance of the UsageOperationsClient -// client. -func NewUsageOperationsClient(subscriptionID string) UsageOperationsClient { - return NewUsageOperationsClientWithBaseURI(DefaultBaseURI, subscriptionID) +// NewUsageClient creates an instance of the UsageClient client. +func NewUsageClient(subscriptionID string) UsageClient { + return NewUsageClientWithBaseURI(DefaultBaseURI, subscriptionID) } -// NewUsageOperationsClientWithBaseURI creates an instance of the -// UsageOperationsClient client. -func NewUsageOperationsClientWithBaseURI(baseURI string, subscriptionID string) UsageOperationsClient { - return UsageOperationsClient{NewWithBaseURI(baseURI, subscriptionID)} +// NewUsageClientWithBaseURI creates an instance of the UsageClient client. +func NewUsageClientWithBaseURI(baseURI string, subscriptionID string) UsageClient { + return UsageClient{NewWithBaseURI(baseURI, subscriptionID)} } // List gets, for the specified location, the current compute resource usage @@ -47,41 +45,44 @@ func NewUsageOperationsClientWithBaseURI(baseURI string, subscriptionID string) // subscription. // // location is the location for which resource usage is queried. -func (client UsageOperationsClient) List(location string) (result ListUsagesResult, err error) { +func (client UsageClient) List(location string) (result ListUsagesResult, err error) { if err := validation.Validate([]validation.Validation{ {TargetValue: location, Constraints: []validation.Constraint{{Target: "location", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewErrorWithValidationError(err, "compute.UsageOperationsClient", "List") + return result, validation.NewErrorWithValidationError(err, "compute.UsageClient", "List") } req, err := client.ListPreparer(location) if err != nil { - return result, autorest.NewErrorWithError(err, "compute.UsageOperationsClient", "List", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "compute.UsageClient", "List", nil, "Failure preparing request") + return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.UsageOperationsClient", "List", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "compute.UsageClient", "List", resp, "Failure sending request") + return } result, err = client.ListResponder(resp) if err != nil { - err = autorest.NewErrorWithError(err, "compute.UsageOperationsClient", "List", resp, "Failure responding to request") + err = autorest.NewErrorWithError(err, "compute.UsageClient", "List", resp, "Failure responding to request") } return } // ListPreparer prepares the List request. -func (client UsageOperationsClient) ListPreparer(location string) (*http.Request, error) { +func (client UsageClient) ListPreparer(location string) (*http.Request, error) { pathParameters := map[string]interface{}{ "location": autorest.Encode("path", location), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -94,13 +95,13 @@ 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) { +func (client UsageClient) ListSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always // closes the http.Response Body. -func (client UsageOperationsClient) ListResponder(resp *http.Response) (result ListUsagesResult, err error) { +func (client UsageClient) ListResponder(resp *http.Response) (result ListUsagesResult, err error) { err = autorest.Respond( resp, client.ByInspecting(), @@ -112,10 +113,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, err error) { +func (client UsageClient) ListNextResults(lastResults ListUsagesResult) (result ListUsagesResult, err error) { req, err := lastResults.ListUsagesResultPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "compute.UsageOperationsClient", "List", nil, "Failure preparing next results request") + return result, autorest.NewErrorWithError(err, "compute.UsageClient", "List", nil, "Failure preparing next results request") } if req == nil { return @@ -124,12 +125,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, "Failure sending next results request") + return result, autorest.NewErrorWithError(err, "compute.UsageClient", "List", resp, "Failure sending next results request") } result, err = client.ListResponder(resp) if err != nil { - err = autorest.NewErrorWithError(err, "compute.UsageOperationsClient", "List", resp, "Failure responding to next results request") + err = autorest.NewErrorWithError(err, "compute.UsageClient", "List", resp, "Failure responding to next results 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 old mode 100644 new mode 100755 index 3c4783ed6fa4..a5318ebf7983 --- 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,30 +14,16 @@ 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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. -import ( - "fmt" -) - -const ( - major = "7" - minor = "0" - 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 arm-%s/%s" -) - // UserAgent returns the UserAgent string to use when sending http.Requests. func UserAgent() string { - return fmt.Sprintf(userAgentFormat, Version(), "compute", "2016-03-30") + return "Azure-SDK-For-Go/v10.0.2-beta arm-compute/2016-04-30-preview" } // Version returns the semantic version (see http://semver.org) of the client. func Version() string { - return fmt.Sprintf(semVerFormat, major, minor, patch, tag) + return "v10.0.2-beta" } 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 old mode 100644 new mode 100755 index 089ebe10e820..fcd122704284 --- 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,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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -35,8 +35,8 @@ func NewVirtualMachineExtensionImagesClient(subscriptionID string) VirtualMachin return NewVirtualMachineExtensionImagesClientWithBaseURI(DefaultBaseURI, subscriptionID) } -// NewVirtualMachineExtensionImagesClientWithBaseURI creates an instance of -// the VirtualMachineExtensionImagesClient client. +// NewVirtualMachineExtensionImagesClientWithBaseURI creates an instance of the +// VirtualMachineExtensionImagesClient client. func NewVirtualMachineExtensionImagesClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachineExtensionImagesClient { return VirtualMachineExtensionImagesClient{NewWithBaseURI(baseURI, subscriptionID)} } @@ -46,13 +46,15 @@ func NewVirtualMachineExtensionImagesClientWithBaseURI(baseURI string, subscript 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "Get", nil, "Failure preparing request") + return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "Get", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "Get", resp, "Failure sending request") + return } result, err = client.GetResponder(resp) @@ -73,8 +75,9 @@ func (client VirtualMachineExtensionImagesClient) GetPreparer(location string, p "version": autorest.Encode("path", version), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -109,13 +112,15 @@ func (client VirtualMachineExtensionImagesClient) GetResponder(resp *http.Respon func (client VirtualMachineExtensionImagesClient) ListTypes(location string, publisherName string) (result ListVirtualMachineExtensionImage, err error) { req, err := client.ListTypesPreparer(location, publisherName) if err != nil { - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListTypes", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListTypes", nil, "Failure preparing request") + return } resp, err := client.ListTypesSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListTypes", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListTypes", resp, "Failure sending request") + return } result, err = client.ListTypesResponder(resp) @@ -134,8 +139,9 @@ func (client VirtualMachineExtensionImagesClient) ListTypesPreparer(location str "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -171,13 +177,15 @@ func (client VirtualMachineExtensionImagesClient) ListTypesResponder(resp *http. func (client VirtualMachineExtensionImagesClient) ListVersions(location string, publisherName string, typeParameter string, filter string, top *int32, orderby string) (result ListVirtualMachineExtensionImage, err error) { req, err := client.ListVersionsPreparer(location, publisherName, typeParameter, filter, top, orderby) if err != nil { - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListVersions", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListVersions", nil, "Failure preparing request") + return } resp, err := client.ListVersionsSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListVersions", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListVersions", resp, "Failure sending request") + return } result, err = client.ListVersionsResponder(resp) @@ -197,8 +205,9 @@ func (client VirtualMachineExtensionImagesClient) ListVersionsPreparer(location "type": autorest.Encode("path", typeParameter), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } if len(filter) > 0 { queryParameters["$filter"] = autorest.Encode("query", filter) 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 old mode 100644 new mode 100755 index d94a2b9683a4..7a876cfef1a2 --- 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,14 +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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" "net/http" ) @@ -47,49 +46,56 @@ func NewVirtualMachineExtensionsClientWithBaseURI(baseURI string, subscriptionID // 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 +// 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. +// 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, cancel <-chan struct{}) (result autorest.Response, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: extensionParameters, - Constraints: []validation.Constraint{{Target: "extensionParameters.VirtualMachineExtensionProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "extensionParameters.VirtualMachineExtensionProperties.ProvisioningState", Name: validation.ReadOnly, Rule: true, Chain: nil}}}}}}); err != nil { - return result, validation.NewErrorWithValidationError(err, "compute.VirtualMachineExtensionsClient", "CreateOrUpdate") - } - - req, err := client.CreateOrUpdatePreparer(resourceGroupName, vmName, vmExtensionName, extensionParameters, cancel) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "CreateOrUpdate", nil, "Failure preparing request") - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "CreateOrUpdate", resp, "Failure sending request") - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "CreateOrUpdate", resp, "Failure responding to request") - } - - return +func (client VirtualMachineExtensionsClient) CreateOrUpdate(resourceGroupName string, VMName string, VMExtensionName string, extensionParameters VirtualMachineExtension, cancel <-chan struct{}) (<-chan VirtualMachineExtension, <-chan error) { + resultChan := make(chan VirtualMachineExtension, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result VirtualMachineExtension + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.CreateOrUpdatePreparer(resourceGroupName, VMName, VMExtensionName, extensionParameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "CreateOrUpdate", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualMachineExtensionsClient) CreateOrUpdatePreparer(resourceGroupName string, vmName string, vmExtensionName string, extensionParameters VirtualMachineExtension, cancel <-chan struct{}) (*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": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmExtensionName": autorest.Encode("path", vmExtensionName), - "vmName": autorest.Encode("path", vmName), + "vmExtensionName": autorest.Encode("path", VMExtensionName), + "vmName": autorest.Encode("path", VMName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -112,55 +118,70 @@ func (client VirtualMachineExtensionsClient) CreateOrUpdateSender(req *http.Requ // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client VirtualMachineExtensionsClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualMachineExtensionsClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualMachineExtension, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } // 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. +// 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 +// 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, 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", nil, "Failure preparing request") - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "Delete", resp, "Failure sending request") - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "Delete", resp, "Failure responding to request") - } - - return +func (client VirtualMachineExtensionsClient) Delete(resourceGroupName string, VMName string, VMExtensionName string, cancel <-chan struct{}) (<-chan OperationStatusResponse, <-chan error) { + resultChan := make(chan OperationStatusResponse, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result OperationStatusResponse + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeletePreparer(resourceGroupName, VMName, VMExtensionName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "Delete", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // DeletePreparer prepares the Delete request. -func (client VirtualMachineExtensionsClient) DeletePreparer(resourceGroupName string, vmName string, vmExtensionName string, cancel <-chan struct{}) (*http.Request, error) { +func (client VirtualMachineExtensionsClient) DeletePreparer(resourceGroupName string, VMName string, VMExtensionName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmExtensionName": autorest.Encode("path", vmExtensionName), - "vmName": autorest.Encode("path", vmName), + "vmExtensionName": autorest.Encode("path", VMExtensionName), + "vmName": autorest.Encode("path", VMName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -181,32 +202,35 @@ func (client VirtualMachineExtensionsClient) DeleteSender(req *http.Request) (*h // DeleteResponder handles the response to the Delete request. The method always // closes the http.Response Body. -func (client VirtualMachineExtensionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualMachineExtensionsClient) DeleteResponder(resp *http.Response) (result OperationStatusResponse, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } // Get the operation to get the extension. // -// resourceGroupName is the name of the resource group. vmName is the name of -// 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, err error) { - req, err := client.GetPreparer(resourceGroupName, vmName, vmExtensionName, expand) +// resourceGroupName is the name of the resource group. VMName is the name of +// 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, err error) { + req, err := client.GetPreparer(resourceGroupName, VMName, VMExtensionName, expand) if err != nil { - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "Get", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "Get", nil, "Failure preparing request") + return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "Get", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionsClient", "Get", resp, "Failure sending request") + return } result, err = client.GetResponder(resp) @@ -218,16 +242,17 @@ func (client VirtualMachineExtensionsClient) Get(resourceGroupName string, vmNam } // GetPreparer prepares the Get request. -func (client VirtualMachineExtensionsClient) GetPreparer(resourceGroupName string, vmName string, vmExtensionName string, expand string) (*http.Request, error) { +func (client VirtualMachineExtensionsClient) GetPreparer(resourceGroupName string, VMName string, VMExtensionName string, expand string) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmExtensionName": autorest.Encode("path", vmExtensionName), - "vmName": autorest.Encode("path", vmName), + "vmExtensionName": autorest.Encode("path", VMExtensionName), + "vmName": autorest.Encode("path", VMName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } if len(expand) > 0 { queryParameters["$expand"] = autorest.Encode("query", expand) 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 old mode 100644 new mode 100755 index db1877789378..6c090568f520 --- 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,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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -49,13 +49,15 @@ func NewVirtualMachineImagesClientWithBaseURI(baseURI string, subscriptionID str 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "Get", nil, "Failure preparing request") + return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "Get", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "Get", resp, "Failure sending request") + return } result, err = client.GetResponder(resp) @@ -77,8 +79,9 @@ func (client VirtualMachineImagesClient) GetPreparer(location string, publisherN "version": autorest.Encode("path", version), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -117,13 +120,15 @@ func (client VirtualMachineImagesClient) GetResponder(resp *http.Response) (resu 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "List", nil, "Failure preparing request") + return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "List", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "List", resp, "Failure sending request") + return } result, err = client.ListResponder(resp) @@ -144,8 +149,9 @@ func (client VirtualMachineImagesClient) ListPreparer(location string, publisher "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } if len(filter) > 0 { queryParameters["$filter"] = autorest.Encode("query", filter) @@ -192,13 +198,15 @@ func (client VirtualMachineImagesClient) ListResponder(resp *http.Response) (res 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListOffers", nil, "Failure preparing request") + return } resp, err := client.ListOffersSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListOffers", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListOffers", resp, "Failure sending request") + return } result, err = client.ListOffersResponder(resp) @@ -217,8 +225,9 @@ func (client VirtualMachineImagesClient) ListOffersPreparer(location string, pub "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -255,13 +264,15 @@ func (client VirtualMachineImagesClient) ListOffersResponder(resp *http.Response 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListPublishers", nil, "Failure preparing request") + return } resp, err := client.ListPublishersSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListPublishers", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListPublishers", resp, "Failure sending request") + return } result, err = client.ListPublishersResponder(resp) @@ -279,8 +290,9 @@ func (client VirtualMachineImagesClient) ListPublishersPreparer(location string) "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -318,13 +330,15 @@ func (client VirtualMachineImagesClient) ListPublishersResponder(resp *http.Resp 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListSkus", nil, "Failure preparing request") + return } resp, err := client.ListSkusSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListSkus", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListSkus", resp, "Failure sending request") + return } result, err = client.ListSkusResponder(resp) @@ -344,8 +358,9 @@ func (client VirtualMachineImagesClient) ListSkusPreparer(location string, publi "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( 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 old mode 100644 new mode 100755 index 626319737ce1..686b7ace2327 --- 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,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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -43,52 +43,69 @@ func NewVirtualMachinesClientWithBaseURI(baseURI string, subscriptionID string) } // Capture captures the VM by copying virtual hard disks of the VM and outputs -// a 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. +// a 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 +// 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, cancel <-chan struct{}) (result autorest.Response, err error) { +func (client VirtualMachinesClient) Capture(resourceGroupName string, VMName string, parameters VirtualMachineCaptureParameters, cancel <-chan struct{}) (<-chan VirtualMachineCaptureResult, <-chan error) { + resultChan := make(chan VirtualMachineCaptureResult, 1) + errChan := make(chan error, 1) if err := validation.Validate([]validation.Validation{ {TargetValue: parameters, Constraints: []validation.Constraint{{Target: "parameters.VhdPrefix", Name: validation.Null, Rule: true, Chain: nil}, {Target: "parameters.DestinationContainerName", Name: validation.Null, Rule: true, Chain: nil}, {Target: "parameters.OverwriteVhds", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewErrorWithValidationError(err, "compute.VirtualMachinesClient", "Capture") - } - - req, err := client.CapturePreparer(resourceGroupName, vmName, parameters, cancel) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Capture", nil, "Failure preparing request") - } - - resp, err := client.CaptureSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Capture", resp, "Failure sending request") - } - - result, err = client.CaptureResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Capture", resp, "Failure responding to request") - } - - return + errChan <- validation.NewErrorWithValidationError(err, "compute.VirtualMachinesClient", "Capture") + close(errChan) + close(resultChan) + return resultChan, errChan + } + + go func() { + var err error + var result VirtualMachineCaptureResult + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.CapturePreparer(resourceGroupName, VMName, parameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Capture", nil, "Failure preparing request") + return + } + + resp, err := client.CaptureSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Capture", resp, "Failure sending request") + return + } + + result, err = client.CaptureResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Capture", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // CapturePreparer prepares the Capture request. -func (client VirtualMachinesClient) CapturePreparer(resourceGroupName string, vmName string, parameters VirtualMachineCaptureParameters, cancel <-chan struct{}) (*http.Request, error) { +func (client VirtualMachinesClient) CapturePreparer(resourceGroupName string, VMName string, parameters VirtualMachineCaptureParameters, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmName": autorest.Encode("path", vmName), + "vmName": autorest.Encode("path", VMName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -111,25 +128,111 @@ func (client VirtualMachinesClient) CaptureSender(req *http.Request) (*http.Resp // CaptureResponder handles the response to the Capture request. The method always // closes the http.Response Body. -func (client VirtualMachinesClient) CaptureResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualMachinesClient) CaptureResponder(resp *http.Response) (result VirtualMachineCaptureResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ConvertToManagedDisks converts virtual machine disks from blob-based to +// managed disks. Virtual machine must be stop-deallocated before invoking this +// operation. 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) ConvertToManagedDisks(resourceGroupName string, VMName string, cancel <-chan struct{}) (<-chan OperationStatusResponse, <-chan error) { + resultChan := make(chan OperationStatusResponse, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result OperationStatusResponse + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.ConvertToManagedDisksPreparer(resourceGroupName, VMName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ConvertToManagedDisks", nil, "Failure preparing request") + return + } + + resp, err := client.ConvertToManagedDisksSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ConvertToManagedDisks", resp, "Failure sending request") + return + } + + result, err = client.ConvertToManagedDisksResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ConvertToManagedDisks", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// ConvertToManagedDisksPreparer prepares the ConvertToManagedDisks request. +func (client VirtualMachinesClient) ConvertToManagedDisksPreparer(resourceGroupName string, VMName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmName": autorest.Encode("path", VMName), + } + + const APIVersion = "2016-04-30-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/convertToManagedDisks", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// ConvertToManagedDisksSender sends the ConvertToManagedDisks request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachinesClient) ConvertToManagedDisksSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// ConvertToManagedDisksResponder handles the response to the ConvertToManagedDisks request. The method always +// closes the http.Response Body. +func (client VirtualMachinesClient) ConvertToManagedDisksResponder(resp *http.Response) (result OperationStatusResponse, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } // 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. +// 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, cancel <-chan struct{}) (result autorest.Response, err error) { +// 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, cancel <-chan struct{}) (<-chan VirtualMachine, <-chan error) { + resultChan := make(chan VirtualMachine, 1) + errChan := make(chan error, 1) if err := validation.Validate([]validation.Validation{ {TargetValue: parameters, Constraints: []validation.Constraint{{Target: "parameters.VirtualMachineProperties", Name: validation.Null, Rule: false, @@ -145,47 +248,56 @@ func (client VirtualMachinesClient) CreateOrUpdate(resourceGroupName string, vmN {Target: "parameters.VirtualMachineProperties.StorageProfile.OsDisk.EncryptionSettings.KeyEncryptionKey.SourceVault", Name: validation.Null, Rule: true, Chain: nil}, }}, }}, - {Target: "parameters.VirtualMachineProperties.StorageProfile.OsDisk.Name", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.VirtualMachineProperties.StorageProfile.OsDisk.Vhd", Name: validation.Null, Rule: true, Chain: nil}, }}, }}, - {Target: "parameters.VirtualMachineProperties.ProvisioningState", Name: validation.ReadOnly, Rule: true, Chain: nil}, - {Target: "parameters.VirtualMachineProperties.InstanceView", Name: validation.ReadOnly, Rule: true, Chain: nil}, - {Target: "parameters.VirtualMachineProperties.VMID", Name: validation.ReadOnly, Rule: true, Chain: nil}, - }}, - {Target: "parameters.Resources", Name: validation.ReadOnly, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewErrorWithValidationError(err, "compute.VirtualMachinesClient", "CreateOrUpdate") - } - - req, err := client.CreateOrUpdatePreparer(resourceGroupName, vmName, parameters, cancel) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "CreateOrUpdate", nil, "Failure preparing request") - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "CreateOrUpdate", resp, "Failure sending request") - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "CreateOrUpdate", resp, "Failure responding to request") - } - - return + }}}}}); err != nil { + errChan <- validation.NewErrorWithValidationError(err, "compute.VirtualMachinesClient", "CreateOrUpdate") + close(errChan) + close(resultChan) + return resultChan, errChan + } + + go func() { + var err error + var result VirtualMachine + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.CreateOrUpdatePreparer(resourceGroupName, VMName, parameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "CreateOrUpdate", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client VirtualMachinesClient) CreateOrUpdatePreparer(resourceGroupName string, vmName string, parameters VirtualMachine, cancel <-chan struct{}) (*http.Request, error) { +func (client VirtualMachinesClient) CreateOrUpdatePreparer(resourceGroupName string, VMName string, parameters VirtualMachine, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmName": autorest.Encode("path", vmName), + "vmName": autorest.Encode("path", VMName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -208,13 +320,14 @@ func (client VirtualMachinesClient) CreateOrUpdateSender(req *http.Request) (*ht // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client VirtualMachinesClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualMachinesClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualMachine, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } @@ -224,38 +337,52 @@ func (client VirtualMachinesClient) CreateOrUpdateResponder(resp *http.Response) // 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 +// resourceGroupName is the name of the resource group. VMName is the name of // the virtual machine. -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", nil, "Failure preparing request") - } - - resp, err := client.DeallocateSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Deallocate", resp, "Failure sending request") - } - - result, err = client.DeallocateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Deallocate", resp, "Failure responding to request") - } - - return +func (client VirtualMachinesClient) Deallocate(resourceGroupName string, VMName string, cancel <-chan struct{}) (<-chan OperationStatusResponse, <-chan error) { + resultChan := make(chan OperationStatusResponse, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result OperationStatusResponse + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeallocatePreparer(resourceGroupName, VMName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Deallocate", nil, "Failure preparing request") + return + } + + resp, err := client.DeallocateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Deallocate", resp, "Failure sending request") + return + } + + result, err = client.DeallocateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Deallocate", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // DeallocatePreparer prepares the Deallocate request. -func (client VirtualMachinesClient) DeallocatePreparer(resourceGroupName string, vmName string, cancel <-chan struct{}) (*http.Request, error) { +func (client VirtualMachinesClient) DeallocatePreparer(resourceGroupName string, VMName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmName": autorest.Encode("path", vmName), + "vmName": autorest.Encode("path", VMName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -276,53 +403,68 @@ func (client VirtualMachinesClient) DeallocateSender(req *http.Request) (*http.R // DeallocateResponder handles the response to the Deallocate request. The method always // closes the http.Response Body. -func (client VirtualMachinesClient) DeallocateResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualMachinesClient) DeallocateResponder(resp *http.Response) (result OperationStatusResponse, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } // 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. +// 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 +// resourceGroupName is the name of the resource group. VMName is the name of // the virtual machine. -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", nil, "Failure preparing request") - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Delete", resp, "Failure sending request") - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Delete", resp, "Failure responding to request") - } - - return +func (client VirtualMachinesClient) Delete(resourceGroupName string, VMName string, cancel <-chan struct{}) (<-chan OperationStatusResponse, <-chan error) { + resultChan := make(chan OperationStatusResponse, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result OperationStatusResponse + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeletePreparer(resourceGroupName, VMName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Delete", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // DeletePreparer prepares the Delete request. -func (client VirtualMachinesClient) DeletePreparer(resourceGroupName string, vmName string, cancel <-chan struct{}) (*http.Request, error) { +func (client VirtualMachinesClient) DeletePreparer(resourceGroupName string, VMName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmName": autorest.Encode("path", vmName), + "vmName": autorest.Encode("path", VMName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -343,30 +485,33 @@ func (client VirtualMachinesClient) DeleteSender(req *http.Request) (*http.Respo // DeleteResponder handles the response to the Delete request. The method always // closes the http.Response Body. -func (client VirtualMachinesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualMachinesClient) DeleteResponder(resp *http.Response) (result OperationStatusResponse, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } // Generalize sets the state of the virtual machine to generalized. // -// resourceGroupName is the name of the resource group. vmName is the name of +// 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, err error) { - req, err := client.GeneralizePreparer(resourceGroupName, vmName) +func (client VirtualMachinesClient) Generalize(resourceGroupName string, VMName string) (result OperationStatusResponse, err error) { + req, err := client.GeneralizePreparer(resourceGroupName, VMName) if err != nil { - return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Generalize", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Generalize", nil, "Failure preparing request") + return } resp, err := client.GeneralizeSender(req) if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Generalize", resp, "Failure sending request") + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Generalize", resp, "Failure sending request") + return } result, err = client.GeneralizeResponder(resp) @@ -378,15 +523,16 @@ func (client VirtualMachinesClient) Generalize(resourceGroupName string, vmName } // GeneralizePreparer prepares the Generalize request. -func (client VirtualMachinesClient) GeneralizePreparer(resourceGroupName string, vmName string) (*http.Request, error) { +func (client VirtualMachinesClient) GeneralizePreparer(resourceGroupName string, VMName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmName": autorest.Encode("path", vmName), + "vmName": autorest.Encode("path", VMName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -405,32 +551,35 @@ func (client VirtualMachinesClient) GeneralizeSender(req *http.Request) (*http.R // GeneralizeResponder handles the response to the Generalize request. The method always // closes the http.Response Body. -func (client VirtualMachinesClient) GeneralizeResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualMachinesClient) GeneralizeResponder(resp *http.Response) (result OperationStatusResponse, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } // Get retrieves information about the model view or the instance view of a // virtual machine. // -// resourceGroupName is the name of the resource group. vmName is the name of +// 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. Possible values include: 'instanceView' -func (client VirtualMachinesClient) Get(resourceGroupName string, vmName string, expand InstanceViewTypes) (result VirtualMachine, err error) { - req, err := client.GetPreparer(resourceGroupName, vmName, expand) +// operation. +func (client VirtualMachinesClient) Get(resourceGroupName string, VMName string, expand InstanceViewTypes) (result VirtualMachine, err error) { + req, err := client.GetPreparer(resourceGroupName, VMName, expand) if err != nil { - return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Get", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Get", nil, "Failure preparing request") + return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Get", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Get", resp, "Failure sending request") + return } result, err = client.GetResponder(resp) @@ -442,15 +591,16 @@ func (client VirtualMachinesClient) Get(resourceGroupName string, vmName string, } // GetPreparer prepares the Get request. -func (client VirtualMachinesClient) GetPreparer(resourceGroupName string, vmName string, expand InstanceViewTypes) (*http.Request, error) { +func (client VirtualMachinesClient) GetPreparer(resourceGroupName string, VMName string, expand InstanceViewTypes) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmName": autorest.Encode("path", vmName), + "vmName": autorest.Encode("path", VMName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } if len(string(expand)) > 0 { queryParameters["$expand"] = autorest.Encode("query", expand) @@ -491,13 +641,15 @@ func (client VirtualMachinesClient) GetResponder(resp *http.Response) (result Vi 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "List", nil, "Failure preparing request") + return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "List", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "List", resp, "Failure sending request") + return } result, err = client.ListResponder(resp) @@ -515,8 +667,9 @@ func (client VirtualMachinesClient) ListPreparer(resourceGroupName string) (*htt "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -570,19 +723,21 @@ func (client VirtualMachinesClient) ListNextResults(lastResults VirtualMachineLi return } -// ListAll lists all of the virtual machines in the specified subscription. -// Use the nextLink property in the response to get the next page of virtual +// ListAll lists all of the virtual machines in the specified subscription. Use +// the nextLink property in the response to get the next page of virtual // machines. func (client VirtualMachinesClient) ListAll() (result VirtualMachineListResult, err error) { req, err := client.ListAllPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAll", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAll", nil, "Failure preparing request") + return } resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAll", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAll", resp, "Failure sending request") + return } result, err = client.ListAllResponder(resp) @@ -599,8 +754,9 @@ func (client VirtualMachinesClient) ListAllPreparer() (*http.Request, error) { "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -657,18 +813,20 @@ func (client VirtualMachinesClient) ListAllNextResults(lastResults VirtualMachin // ListAvailableSizes lists all available virtual machine sizes to which the // specified virtual machine can be resized. // -// resourceGroupName is the name of the resource group. vmName is the name of +// 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, err error) { - req, err := client.ListAvailableSizesPreparer(resourceGroupName, vmName) +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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAvailableSizes", nil, "Failure preparing request") + return } resp, err := client.ListAvailableSizesSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAvailableSizes", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "ListAvailableSizes", resp, "Failure sending request") + return } result, err = client.ListAvailableSizesResponder(resp) @@ -680,15 +838,16 @@ func (client VirtualMachinesClient) ListAvailableSizes(resourceGroupName string, } // ListAvailableSizesPreparer prepares the ListAvailableSizes request. -func (client VirtualMachinesClient) ListAvailableSizesPreparer(resourceGroupName string, vmName string) (*http.Request, error) { +func (client VirtualMachinesClient) ListAvailableSizesPreparer(resourceGroupName string, VMName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmName": autorest.Encode("path", vmName), + "vmName": autorest.Encode("path", VMName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -719,44 +878,57 @@ func (client VirtualMachinesClient) ListAvailableSizesResponder(resp *http.Respo } // PowerOff the operation to power off (stop) a virtual machine. The virtual -// machine can be restarted with the same provisioned resources. You are -// still charged for this 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. +// machine can be restarted with the same provisioned resources. You are still +// charged for this 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 +// resourceGroupName is the name of the resource group. VMName is the name of // the virtual machine. -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", nil, "Failure preparing request") - } - - resp, err := client.PowerOffSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "PowerOff", resp, "Failure sending request") - } - - result, err = client.PowerOffResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "PowerOff", resp, "Failure responding to request") - } - - return +func (client VirtualMachinesClient) PowerOff(resourceGroupName string, VMName string, cancel <-chan struct{}) (<-chan OperationStatusResponse, <-chan error) { + resultChan := make(chan OperationStatusResponse, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result OperationStatusResponse + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.PowerOffPreparer(resourceGroupName, VMName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "PowerOff", nil, "Failure preparing request") + return + } + + resp, err := client.PowerOffSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "PowerOff", resp, "Failure sending request") + return + } + + result, err = client.PowerOffResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "PowerOff", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // PowerOffPreparer prepares the PowerOff request. -func (client VirtualMachinesClient) PowerOffPreparer(resourceGroupName string, vmName string, cancel <-chan struct{}) (*http.Request, error) { +func (client VirtualMachinesClient) PowerOffPreparer(resourceGroupName string, VMName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmName": autorest.Encode("path", vmName), + "vmName": autorest.Encode("path", VMName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -777,13 +949,14 @@ func (client VirtualMachinesClient) PowerOffSender(req *http.Request) (*http.Res // PowerOffResponder handles the response to the PowerOff request. The method always // closes the http.Response Body. -func (client VirtualMachinesClient) PowerOffResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualMachinesClient) PowerOffResponder(resp *http.Response) (result OperationStatusResponse, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } @@ -792,38 +965,52 @@ func (client VirtualMachinesClient) PowerOffResponder(resp *http.Response) (resu // 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 +// resourceGroupName is the name of the resource group. VMName is the name of // the virtual machine. -func (client VirtualMachinesClient) Redeploy(resourceGroupName string, vmName string, cancel <-chan struct{}) (result autorest.Response, err error) { - req, err := client.RedeployPreparer(resourceGroupName, vmName, cancel) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Redeploy", nil, "Failure preparing request") - } - - resp, err := client.RedeploySender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Redeploy", resp, "Failure sending request") - } - - result, err = client.RedeployResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Redeploy", resp, "Failure responding to request") - } - - return +func (client VirtualMachinesClient) Redeploy(resourceGroupName string, VMName string, cancel <-chan struct{}) (<-chan OperationStatusResponse, <-chan error) { + resultChan := make(chan OperationStatusResponse, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result OperationStatusResponse + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.RedeployPreparer(resourceGroupName, VMName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Redeploy", nil, "Failure preparing request") + return + } + + resp, err := client.RedeploySender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Redeploy", resp, "Failure sending request") + return + } + + result, err = client.RedeployResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Redeploy", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // RedeployPreparer prepares the Redeploy request. -func (client VirtualMachinesClient) RedeployPreparer(resourceGroupName string, vmName string, cancel <-chan struct{}) (*http.Request, error) { +func (client VirtualMachinesClient) RedeployPreparer(resourceGroupName string, VMName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmName": autorest.Encode("path", vmName), + "vmName": autorest.Encode("path", VMName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -844,53 +1031,68 @@ func (client VirtualMachinesClient) RedeploySender(req *http.Request) (*http.Res // RedeployResponder handles the response to the Redeploy request. The method always // closes the http.Response Body. -func (client VirtualMachinesClient) RedeployResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualMachinesClient) RedeployResponder(resp *http.Response) (result OperationStatusResponse, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } -// 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. +// 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 +// resourceGroupName is the name of the resource group. VMName is the name of // the virtual machine. -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", nil, "Failure preparing request") - } - - resp, err := client.RestartSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Restart", resp, "Failure sending request") - } - - result, err = client.RestartResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Restart", resp, "Failure responding to request") - } - - return +func (client VirtualMachinesClient) Restart(resourceGroupName string, VMName string, cancel <-chan struct{}) (<-chan OperationStatusResponse, <-chan error) { + resultChan := make(chan OperationStatusResponse, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result OperationStatusResponse + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.RestartPreparer(resourceGroupName, VMName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Restart", nil, "Failure preparing request") + return + } + + resp, err := client.RestartSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Restart", resp, "Failure sending request") + return + } + + result, err = client.RestartResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Restart", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // RestartPreparer prepares the Restart request. -func (client VirtualMachinesClient) RestartPreparer(resourceGroupName string, vmName string, cancel <-chan struct{}) (*http.Request, error) { +func (client VirtualMachinesClient) RestartPreparer(resourceGroupName string, VMName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmName": autorest.Encode("path", vmName), + "vmName": autorest.Encode("path", VMName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -911,53 +1113,68 @@ func (client VirtualMachinesClient) RestartSender(req *http.Request) (*http.Resp // RestartResponder handles the response to the Restart request. The method always // closes the http.Response Body. -func (client VirtualMachinesClient) RestartResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualMachinesClient) RestartResponder(resp *http.Response) (result OperationStatusResponse, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } // 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. +// 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 +// resourceGroupName is the name of the resource group. VMName is the name of // the virtual machine. -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", nil, "Failure preparing request") - } - - resp, err := client.StartSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Start", resp, "Failure sending request") - } - - result, err = client.StartResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Start", resp, "Failure responding to request") - } - - return +func (client VirtualMachinesClient) Start(resourceGroupName string, VMName string, cancel <-chan struct{}) (<-chan OperationStatusResponse, <-chan error) { + resultChan := make(chan OperationStatusResponse, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result OperationStatusResponse + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.StartPreparer(resourceGroupName, VMName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Start", nil, "Failure preparing request") + return + } + + resp, err := client.StartSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Start", resp, "Failure sending request") + return + } + + result, err = client.StartResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachinesClient", "Start", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // StartPreparer prepares the Start request. -func (client VirtualMachinesClient) StartPreparer(resourceGroupName string, vmName string, cancel <-chan struct{}) (*http.Request, error) { +func (client VirtualMachinesClient) StartPreparer(resourceGroupName string, VMName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmName": autorest.Encode("path", vmName), + "vmName": autorest.Encode("path", VMName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -978,12 +1195,13 @@ func (client VirtualMachinesClient) StartSender(req *http.Request) (*http.Respon // StartResponder handles the response to the Start request. The method always // closes the http.Response Body. -func (client VirtualMachinesClient) StartResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualMachinesClient) StartResponder(resp *http.Response) (result OperationStatusResponse, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{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 old mode 100644 new mode 100755 index 648e9fa4aec5..53700c8dd9e7 --- 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,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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -43,44 +43,43 @@ func NewVirtualMachineScaleSetsClientWithBaseURI(baseURI string, subscriptionID } // CreateOrUpdate create or update a VM 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. +// 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 the name of -// the VM scale set to create or update. parameters is the scale set object. -func (client VirtualMachineScaleSetsClient) CreateOrUpdate(resourceGroupName string, name string, parameters VirtualMachineScaleSet, cancel <-chan struct{}) (result autorest.Response, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetProperties.VirtualMachineProfile", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetProperties.VirtualMachineProfile.StorageProfile", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetProperties.VirtualMachineProfile.StorageProfile.OsDisk", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualMachineScaleSetProperties.VirtualMachineProfile.StorageProfile.OsDisk.Name", Name: validation.Null, Rule: true, Chain: nil}}}, - }}, - }}, - {Target: "parameters.VirtualMachineScaleSetProperties.ProvisioningState", Name: validation.ReadOnly, Rule: true, Chain: nil}, - }}}}}); err != nil { - return result, validation.NewErrorWithValidationError(err, "compute.VirtualMachineScaleSetsClient", "CreateOrUpdate") - } - - req, err := client.CreateOrUpdatePreparer(resourceGroupName, name, parameters, cancel) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "CreateOrUpdate", nil, "Failure preparing request") - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "CreateOrUpdate", resp, "Failure sending request") - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "CreateOrUpdate", resp, "Failure responding to request") - } - - return +// resourceGroupName is the name of the resource group. name is the name of the +// VM scale set to create or update. parameters is the scale set object. +func (client VirtualMachineScaleSetsClient) CreateOrUpdate(resourceGroupName string, name string, parameters VirtualMachineScaleSet, cancel <-chan struct{}) (<-chan VirtualMachineScaleSet, <-chan error) { + resultChan := make(chan VirtualMachineScaleSet, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result VirtualMachineScaleSet + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.CreateOrUpdatePreparer(resourceGroupName, name, parameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "CreateOrUpdate", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. @@ -91,8 +90,9 @@ func (client VirtualMachineScaleSetsClient) CreateOrUpdatePreparer(resourceGroup "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -115,56 +115,71 @@ func (client VirtualMachineScaleSetsClient) CreateOrUpdateSender(req *http.Reque // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client VirtualMachineScaleSetsClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualMachineScaleSetsClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualMachineScaleSet, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } // Deallocate deallocates specific virtual machines in a VM scale set. Shuts // down the virtual machines and releases the compute resources. You are not // billed for the compute resources that this virtual machine scale set -// deallocates. This method may poll for completion. Polling can be canceled -// by passing the cancel channel argument. The channel will be used to cancel +// deallocates. 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 VM scale set. vmInstanceIDs is a list of virtual machine +// resourceGroupName is the name of the resource group. VMScaleSetName is the +// name of the VM scale set. VMInstanceIDs is a list of virtual machine // instance IDs from the VM scale set. -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", nil, "Failure preparing request") - } - - resp, err := client.DeallocateSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Deallocate", resp, "Failure sending request") - } - - result, err = client.DeallocateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Deallocate", resp, "Failure responding to request") - } - - return +func (client VirtualMachineScaleSetsClient) Deallocate(resourceGroupName string, VMScaleSetName string, VMInstanceIDs *VirtualMachineScaleSetVMInstanceIDs, cancel <-chan struct{}) (<-chan OperationStatusResponse, <-chan error) { + resultChan := make(chan OperationStatusResponse, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result OperationStatusResponse + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeallocatePreparer(resourceGroupName, VMScaleSetName, VMInstanceIDs, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Deallocate", nil, "Failure preparing request") + return + } + + resp, err := client.DeallocateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Deallocate", resp, "Failure sending request") + return + } + + result, err = client.DeallocateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Deallocate", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // DeallocatePreparer prepares the Deallocate request. -func (client VirtualMachineScaleSetsClient) DeallocatePreparer(resourceGroupName string, vmScaleSetName string, vmInstanceIDs *VirtualMachineScaleSetVMInstanceIDs, cancel <-chan struct{}) (*http.Request, error) { +func (client VirtualMachineScaleSetsClient) DeallocatePreparer(resourceGroupName string, VMScaleSetName string, VMInstanceIDs *VirtualMachineScaleSetVMInstanceIDs, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -173,9 +188,9 @@ func (client VirtualMachineScaleSetsClient) DeallocatePreparer(resourceGroupName autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/deallocate", pathParameters), autorest.WithQueryParameters(queryParameters)) - if vmInstanceIDs != nil { + if VMInstanceIDs != nil { preparer = autorest.DecoratePreparer(preparer, - autorest.WithJSON(vmInstanceIDs)) + autorest.WithJSON(VMInstanceIDs)) } return preparer.Prepare(&http.Request{Cancel: cancel}) } @@ -190,52 +205,67 @@ func (client VirtualMachineScaleSetsClient) DeallocateSender(req *http.Request) // DeallocateResponder handles the response to the Deallocate request. The method always // closes the http.Response Body. -func (client VirtualMachineScaleSetsClient) DeallocateResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualMachineScaleSetsClient) DeallocateResponder(resp *http.Response) (result OperationStatusResponse, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } // Delete deletes a VM 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. +// 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 +// resourceGroupName is the name of the resource group. VMScaleSetName is the // name of the VM scale set. -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", nil, "Failure preparing request") - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Delete", resp, "Failure sending request") - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Delete", resp, "Failure responding to request") - } - - return +func (client VirtualMachineScaleSetsClient) Delete(resourceGroupName string, VMScaleSetName string, cancel <-chan struct{}) (<-chan OperationStatusResponse, <-chan error) { + resultChan := make(chan OperationStatusResponse, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result OperationStatusResponse + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeletePreparer(resourceGroupName, VMScaleSetName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Delete", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // DeletePreparer prepares the Delete request. -func (client VirtualMachineScaleSetsClient) DeletePreparer(resourceGroupName string, vmScaleSetName string, cancel <-chan struct{}) (*http.Request, error) { +func (client VirtualMachineScaleSetsClient) DeletePreparer(resourceGroupName string, VMScaleSetName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -256,13 +286,14 @@ func (client VirtualMachineScaleSetsClient) DeleteSender(req *http.Request) (*ht // DeleteResponder handles the response to the Delete request. The method always // closes the http.Response Body. -func (client VirtualMachineScaleSetsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualMachineScaleSetsClient) DeleteResponder(resp *http.Response) (result OperationStatusResponse, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } @@ -271,45 +302,62 @@ func (client VirtualMachineScaleSetsClient) DeleteResponder(resp *http.Response) // 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 VM scale set. vmInstanceIDs is a list of virtual machine +// resourceGroupName is the name of the resource group. VMScaleSetName is the +// name of the VM scale set. VMInstanceIDs is a list of virtual machine // instance IDs from the VM scale set. -func (client VirtualMachineScaleSetsClient) DeleteInstances(resourceGroupName string, vmScaleSetName string, vmInstanceIDs VirtualMachineScaleSetVMInstanceRequiredIDs, cancel <-chan struct{}) (result autorest.Response, err error) { +func (client VirtualMachineScaleSetsClient) DeleteInstances(resourceGroupName string, VMScaleSetName string, VMInstanceIDs VirtualMachineScaleSetVMInstanceRequiredIDs, cancel <-chan struct{}) (<-chan OperationStatusResponse, <-chan error) { + resultChan := make(chan OperationStatusResponse, 1) + errChan := make(chan error, 1) if err := validation.Validate([]validation.Validation{ - {TargetValue: vmInstanceIDs, - Constraints: []validation.Constraint{{Target: "vmInstanceIDs.InstanceIds", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewErrorWithValidationError(err, "compute.VirtualMachineScaleSetsClient", "DeleteInstances") - } - - req, err := client.DeleteInstancesPreparer(resourceGroupName, vmScaleSetName, vmInstanceIDs, cancel) - if err != nil { - 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, "Failure sending request") - } - - result, err = client.DeleteInstancesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "DeleteInstances", resp, "Failure responding to request") - } - - return + {TargetValue: VMInstanceIDs, + Constraints: []validation.Constraint{{Target: "VMInstanceIDs.InstanceIds", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + errChan <- validation.NewErrorWithValidationError(err, "compute.VirtualMachineScaleSetsClient", "DeleteInstances") + close(errChan) + close(resultChan) + return resultChan, errChan + } + + go func() { + var err error + var result OperationStatusResponse + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeleteInstancesPreparer(resourceGroupName, VMScaleSetName, VMInstanceIDs, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "DeleteInstances", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteInstancesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "DeleteInstances", resp, "Failure sending request") + return + } + + result, err = client.DeleteInstancesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "DeleteInstances", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // DeleteInstancesPreparer prepares the DeleteInstances request. -func (client VirtualMachineScaleSetsClient) DeleteInstancesPreparer(resourceGroupName string, vmScaleSetName string, vmInstanceIDs VirtualMachineScaleSetVMInstanceRequiredIDs, cancel <-chan struct{}) (*http.Request, error) { +func (client VirtualMachineScaleSetsClient) DeleteInstancesPreparer(resourceGroupName string, VMScaleSetName string, VMInstanceIDs VirtualMachineScaleSetVMInstanceRequiredIDs, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -317,7 +365,7 @@ func (client VirtualMachineScaleSetsClient) DeleteInstancesPreparer(resourceGrou autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/delete", pathParameters), - autorest.WithJSON(vmInstanceIDs), + autorest.WithJSON(VMInstanceIDs), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare(&http.Request{Cancel: cancel}) } @@ -332,30 +380,33 @@ func (client VirtualMachineScaleSetsClient) DeleteInstancesSender(req *http.Requ // DeleteInstancesResponder handles the response to the DeleteInstances request. The method always // closes the http.Response Body. -func (client VirtualMachineScaleSetsClient) DeleteInstancesResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualMachineScaleSetsClient) DeleteInstancesResponder(resp *http.Response) (result OperationStatusResponse, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } // Get display information about a virtual machine scale set. // -// resourceGroupName is the name of the resource group. vmScaleSetName is the +// resourceGroupName is the name of the resource group. VMScaleSetName is the // name of the VM scale set. -func (client VirtualMachineScaleSetsClient) Get(resourceGroupName string, vmScaleSetName string) (result VirtualMachineScaleSet, err error) { - req, err := client.GetPreparer(resourceGroupName, vmScaleSetName) +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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Get", nil, "Failure preparing request") + return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Get", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Get", resp, "Failure sending request") + return } result, err = client.GetResponder(resp) @@ -367,15 +418,16 @@ func (client VirtualMachineScaleSetsClient) Get(resourceGroupName string, vmScal } // GetPreparer prepares the Get request. -func (client VirtualMachineScaleSetsClient) GetPreparer(resourceGroupName string, vmScaleSetName string) (*http.Request, error) { +func (client VirtualMachineScaleSetsClient) GetPreparer(resourceGroupName string, VMScaleSetName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -407,18 +459,20 @@ func (client VirtualMachineScaleSetsClient) GetResponder(resp *http.Response) (r // GetInstanceView gets the status of a VM scale set instance. // -// resourceGroupName is the name of the resource group. vmScaleSetName is the +// resourceGroupName is the name of the resource group. VMScaleSetName is the // name of the VM scale set. -func (client VirtualMachineScaleSetsClient) GetInstanceView(resourceGroupName string, vmScaleSetName string) (result VirtualMachineScaleSetInstanceView, err error) { - req, err := client.GetInstanceViewPreparer(resourceGroupName, vmScaleSetName) +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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "GetInstanceView", nil, "Failure preparing request") + return } resp, err := client.GetInstanceViewSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "GetInstanceView", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "GetInstanceView", resp, "Failure sending request") + return } result, err = client.GetInstanceViewResponder(resp) @@ -430,15 +484,16 @@ func (client VirtualMachineScaleSetsClient) GetInstanceView(resourceGroupName st } // GetInstanceViewPreparer prepares the GetInstanceView request. -func (client VirtualMachineScaleSetsClient) GetInstanceViewPreparer(resourceGroupName string, vmScaleSetName string) (*http.Request, error) { +func (client VirtualMachineScaleSetsClient) GetInstanceViewPreparer(resourceGroupName string, VMScaleSetName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -474,13 +529,15 @@ func (client VirtualMachineScaleSetsClient) GetInstanceViewResponder(resp *http. 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "List", nil, "Failure preparing request") + return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "List", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "List", resp, "Failure sending request") + return } result, err = client.ListResponder(resp) @@ -498,8 +555,9 @@ func (client VirtualMachineScaleSetsClient) ListPreparer(resourceGroupName strin "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -554,19 +612,21 @@ func (client VirtualMachineScaleSetsClient) ListNextResults(lastResults VirtualM } // ListAll gets a list of all VM Scale Sets in the subscription, regardless of -// the associated resource group. Use nextLink property in the response to -// get the next page of VM Scale Sets. Do this till nextLink is not null to -// fetch all the VM Scale Sets. +// the associated resource group. Use nextLink property in the response to get +// the next page of VM Scale Sets. Do this till nextLink is not null to fetch +// all the VM Scale Sets. func (client VirtualMachineScaleSetsClient) ListAll() (result VirtualMachineScaleSetListWithLinkResult, err error) { req, err := client.ListAllPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListAll", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListAll", nil, "Failure preparing request") + return } resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListAll", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListAll", resp, "Failure sending request") + return } result, err = client.ListAllResponder(resp) @@ -583,8 +643,9 @@ func (client VirtualMachineScaleSetsClient) ListAllPreparer() (*http.Request, er "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -641,18 +702,20 @@ func (client VirtualMachineScaleSetsClient) ListAllNextResults(lastResults Virtu // ListSkus gets a list of SKUs available for your VM scale set, including the // minimum and maximum VM instances allowed for each SKU. // -// resourceGroupName is the name of the resource group. vmScaleSetName is the +// resourceGroupName is the name of the resource group. VMScaleSetName is the // name of the VM scale set. -func (client VirtualMachineScaleSetsClient) ListSkus(resourceGroupName string, vmScaleSetName string) (result VirtualMachineScaleSetListSkusResult, err error) { - req, err := client.ListSkusPreparer(resourceGroupName, vmScaleSetName) +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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListSkus", nil, "Failure preparing request") + return } resp, err := client.ListSkusSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListSkus", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ListSkus", resp, "Failure sending request") + return } result, err = client.ListSkusResponder(resp) @@ -664,15 +727,16 @@ func (client VirtualMachineScaleSetsClient) ListSkus(resourceGroupName string, v } // ListSkusPreparer prepares the ListSkus request. -func (client VirtualMachineScaleSetsClient) ListSkusPreparer(resourceGroupName string, vmScaleSetName string) (*http.Request, error) { +func (client VirtualMachineScaleSetsClient) ListSkusPreparer(resourceGroupName string, VMScaleSetName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -729,43 +793,57 @@ func (client VirtualMachineScaleSetsClient) ListSkusNextResults(lastResults Virt // PowerOff power off (stop) one or more virtual machines in a VM scale set. // Note that resources are still attached and you are getting charged for the // resources. Instead, use deallocate to release resources and avoid charges. -// 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. +// 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 VM scale set. vmInstanceIDs is a list of virtual machine +// resourceGroupName is the name of the resource group. VMScaleSetName is the +// name of the VM scale set. VMInstanceIDs is a list of virtual machine // instance IDs from the VM scale set. -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", nil, "Failure preparing request") - } - - resp, err := client.PowerOffSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "PowerOff", resp, "Failure sending request") - } - - result, err = client.PowerOffResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "PowerOff", resp, "Failure responding to request") - } - - return +func (client VirtualMachineScaleSetsClient) PowerOff(resourceGroupName string, VMScaleSetName string, VMInstanceIDs *VirtualMachineScaleSetVMInstanceIDs, cancel <-chan struct{}) (<-chan OperationStatusResponse, <-chan error) { + resultChan := make(chan OperationStatusResponse, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result OperationStatusResponse + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.PowerOffPreparer(resourceGroupName, VMScaleSetName, VMInstanceIDs, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "PowerOff", nil, "Failure preparing request") + return + } + + resp, err := client.PowerOffSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "PowerOff", resp, "Failure sending request") + return + } + + result, err = client.PowerOffResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "PowerOff", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // PowerOffPreparer prepares the PowerOff request. -func (client VirtualMachineScaleSetsClient) PowerOffPreparer(resourceGroupName string, vmScaleSetName string, vmInstanceIDs *VirtualMachineScaleSetVMInstanceIDs, cancel <-chan struct{}) (*http.Request, error) { +func (client VirtualMachineScaleSetsClient) PowerOffPreparer(resourceGroupName string, VMScaleSetName string, VMInstanceIDs *VirtualMachineScaleSetVMInstanceIDs, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -774,9 +852,9 @@ func (client VirtualMachineScaleSetsClient) PowerOffPreparer(resourceGroupName s autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/poweroff", pathParameters), autorest.WithQueryParameters(queryParameters)) - if vmInstanceIDs != nil { + if VMInstanceIDs != nil { preparer = autorest.DecoratePreparer(preparer, - autorest.WithJSON(vmInstanceIDs)) + autorest.WithJSON(VMInstanceIDs)) } return preparer.Prepare(&http.Request{Cancel: cancel}) } @@ -791,53 +869,68 @@ func (client VirtualMachineScaleSetsClient) PowerOffSender(req *http.Request) (* // PowerOffResponder handles the response to the PowerOff request. The method always // closes the http.Response Body. -func (client VirtualMachineScaleSetsClient) PowerOffResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualMachineScaleSetsClient) PowerOffResponder(resp *http.Response) (result OperationStatusResponse, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } -// Reimage reimages (upgrade the operating system) one or more virtual -// machines in a VM 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. +// Reimage reimages (upgrade the operating system) one or more virtual machines +// in a VM 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 +// resourceGroupName is the name of the resource group. VMScaleSetName is the // name of the VM scale set. -func (client VirtualMachineScaleSetsClient) Reimage(resourceGroupName string, vmScaleSetName string, cancel <-chan struct{}) (result autorest.Response, err error) { - req, err := client.ReimagePreparer(resourceGroupName, vmScaleSetName, cancel) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Reimage", nil, "Failure preparing request") - } - - resp, err := client.ReimageSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Reimage", resp, "Failure sending request") - } - - result, err = client.ReimageResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Reimage", resp, "Failure responding to request") - } - - return +func (client VirtualMachineScaleSetsClient) Reimage(resourceGroupName string, VMScaleSetName string, cancel <-chan struct{}) (<-chan OperationStatusResponse, <-chan error) { + resultChan := make(chan OperationStatusResponse, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result OperationStatusResponse + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.ReimagePreparer(resourceGroupName, VMScaleSetName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Reimage", nil, "Failure preparing request") + return + } + + resp, err := client.ReimageSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Reimage", resp, "Failure sending request") + return + } + + result, err = client.ReimageResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Reimage", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // ReimagePreparer prepares the Reimage request. -func (client VirtualMachineScaleSetsClient) ReimagePreparer(resourceGroupName string, vmScaleSetName string, cancel <-chan struct{}) (*http.Request, error) { +func (client VirtualMachineScaleSetsClient) ReimagePreparer(resourceGroupName string, VMScaleSetName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -858,54 +951,152 @@ func (client VirtualMachineScaleSetsClient) ReimageSender(req *http.Request) (*h // ReimageResponder handles the response to the Reimage request. The method always // closes the http.Response Body. -func (client VirtualMachineScaleSetsClient) ReimageResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualMachineScaleSetsClient) ReimageResponder(resp *http.Response) (result OperationStatusResponse, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } -// Restart restarts one or more virtual machines in a VM 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. +// ReimageAll reimages all the disks ( including data disks ) in the virtual +// machines in a virtual machine scale set. This operation is only supported +// for managed disks. 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 VM scale set. vmInstanceIDs is a list of virtual machine -// instance IDs from the VM scale set. -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", nil, "Failure preparing request") - } +// resourceGroupName is the name of the resource group. VMScaleSetName is the +// name of the VM scale set. +func (client VirtualMachineScaleSetsClient) ReimageAll(resourceGroupName string, VMScaleSetName string, cancel <-chan struct{}) (<-chan OperationStatusResponse, <-chan error) { + resultChan := make(chan OperationStatusResponse, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result OperationStatusResponse + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.ReimageAllPreparer(resourceGroupName, VMScaleSetName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ReimageAll", nil, "Failure preparing request") + return + } + + resp, err := client.ReimageAllSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ReimageAll", resp, "Failure sending request") + return + } + + result, err = client.ReimageAllResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "ReimageAll", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} - resp, err := client.RestartSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Restart", resp, "Failure sending request") +// ReimageAllPreparer prepares the ReimageAll request. +func (client VirtualMachineScaleSetsClient) ReimageAllPreparer(resourceGroupName string, VMScaleSetName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } - result, err = client.RestartResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Restart", resp, "Failure responding to request") + const APIVersion = "2016-04-30-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, } + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/reimageall", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// ReimageAllSender sends the ReimageAll request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineScaleSetsClient) ReimageAllSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// ReimageAllResponder handles the response to the ReimageAll request. The method always +// closes the http.Response Body. +func (client VirtualMachineScaleSetsClient) ReimageAllResponder(resp *http.Response) (result OperationStatusResponse, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} return } +// Restart restarts one or more virtual machines in a VM 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 VM scale set. VMInstanceIDs is a list of virtual machine +// instance IDs from the VM scale set. +func (client VirtualMachineScaleSetsClient) Restart(resourceGroupName string, VMScaleSetName string, VMInstanceIDs *VirtualMachineScaleSetVMInstanceIDs, cancel <-chan struct{}) (<-chan OperationStatusResponse, <-chan error) { + resultChan := make(chan OperationStatusResponse, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result OperationStatusResponse + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.RestartPreparer(resourceGroupName, VMScaleSetName, VMInstanceIDs, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Restart", nil, "Failure preparing request") + return + } + + resp, err := client.RestartSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Restart", resp, "Failure sending request") + return + } + + result, err = client.RestartResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Restart", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + // RestartPreparer prepares the Restart request. -func (client VirtualMachineScaleSetsClient) RestartPreparer(resourceGroupName string, vmScaleSetName string, vmInstanceIDs *VirtualMachineScaleSetVMInstanceIDs, cancel <-chan struct{}) (*http.Request, error) { +func (client VirtualMachineScaleSetsClient) RestartPreparer(resourceGroupName string, VMScaleSetName string, VMInstanceIDs *VirtualMachineScaleSetVMInstanceIDs, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -914,9 +1105,9 @@ func (client VirtualMachineScaleSetsClient) RestartPreparer(resourceGroupName st autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/restart", pathParameters), autorest.WithQueryParameters(queryParameters)) - if vmInstanceIDs != nil { + if VMInstanceIDs != nil { preparer = autorest.DecoratePreparer(preparer, - autorest.WithJSON(vmInstanceIDs)) + autorest.WithJSON(VMInstanceIDs)) } return preparer.Prepare(&http.Request{Cancel: cancel}) } @@ -931,54 +1122,69 @@ func (client VirtualMachineScaleSetsClient) RestartSender(req *http.Request) (*h // RestartResponder handles the response to the Restart request. The method always // closes the http.Response Body. -func (client VirtualMachineScaleSetsClient) RestartResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualMachineScaleSetsClient) RestartResponder(resp *http.Response) (result OperationStatusResponse, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } -// Start starts one or more virtual machines in a VM 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. +// Start starts one or more virtual machines in a VM 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 VM scale set. vmInstanceIDs is a list of virtual machine +// resourceGroupName is the name of the resource group. VMScaleSetName is the +// name of the VM scale set. VMInstanceIDs is a list of virtual machine // instance IDs from the VM scale set. -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", nil, "Failure preparing request") - } - - resp, err := client.StartSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Start", resp, "Failure sending request") - } - - result, err = client.StartResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Start", resp, "Failure responding to request") - } - - return +func (client VirtualMachineScaleSetsClient) Start(resourceGroupName string, VMScaleSetName string, VMInstanceIDs *VirtualMachineScaleSetVMInstanceIDs, cancel <-chan struct{}) (<-chan OperationStatusResponse, <-chan error) { + resultChan := make(chan OperationStatusResponse, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result OperationStatusResponse + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.StartPreparer(resourceGroupName, VMScaleSetName, VMInstanceIDs, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Start", nil, "Failure preparing request") + return + } + + resp, err := client.StartSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Start", resp, "Failure sending request") + return + } + + result, err = client.StartResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "Start", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // StartPreparer prepares the Start request. -func (client VirtualMachineScaleSetsClient) StartPreparer(resourceGroupName string, vmScaleSetName string, vmInstanceIDs *VirtualMachineScaleSetVMInstanceIDs, cancel <-chan struct{}) (*http.Request, error) { +func (client VirtualMachineScaleSetsClient) StartPreparer(resourceGroupName string, VMScaleSetName string, VMInstanceIDs *VirtualMachineScaleSetVMInstanceIDs, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -987,9 +1193,9 @@ func (client VirtualMachineScaleSetsClient) StartPreparer(resourceGroupName stri autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/start", pathParameters), autorest.WithQueryParameters(queryParameters)) - if vmInstanceIDs != nil { + if VMInstanceIDs != nil { preparer = autorest.DecoratePreparer(preparer, - autorest.WithJSON(vmInstanceIDs)) + autorest.WithJSON(VMInstanceIDs)) } return preparer.Prepare(&http.Request{Cancel: cancel}) } @@ -1004,60 +1210,78 @@ func (client VirtualMachineScaleSetsClient) StartSender(req *http.Request) (*htt // StartResponder handles the response to the Start request. The method always // closes the http.Response Body. -func (client VirtualMachineScaleSetsClient) StartResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualMachineScaleSetsClient) StartResponder(resp *http.Response) (result OperationStatusResponse, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } // UpdateInstances upgrades one or more virtual machines to the latest SKU set -// in the VM scale set model. 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. +// in the VM scale set model. 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 VM scale set. vmInstanceIDs is a list of virtual machine +// resourceGroupName is the name of the resource group. VMScaleSetName is the +// name of the VM scale set. VMInstanceIDs is a list of virtual machine // instance IDs from the VM scale set. -func (client VirtualMachineScaleSetsClient) UpdateInstances(resourceGroupName string, vmScaleSetName string, vmInstanceIDs VirtualMachineScaleSetVMInstanceRequiredIDs, cancel <-chan struct{}) (result autorest.Response, err error) { +func (client VirtualMachineScaleSetsClient) UpdateInstances(resourceGroupName string, VMScaleSetName string, VMInstanceIDs VirtualMachineScaleSetVMInstanceRequiredIDs, cancel <-chan struct{}) (<-chan OperationStatusResponse, <-chan error) { + resultChan := make(chan OperationStatusResponse, 1) + errChan := make(chan error, 1) if err := validation.Validate([]validation.Validation{ - {TargetValue: vmInstanceIDs, - Constraints: []validation.Constraint{{Target: "vmInstanceIDs.InstanceIds", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewErrorWithValidationError(err, "compute.VirtualMachineScaleSetsClient", "UpdateInstances") - } - - req, err := client.UpdateInstancesPreparer(resourceGroupName, vmScaleSetName, vmInstanceIDs, cancel) - if err != nil { - 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, "Failure sending request") - } - - result, err = client.UpdateInstancesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "UpdateInstances", resp, "Failure responding to request") - } - - return + {TargetValue: VMInstanceIDs, + Constraints: []validation.Constraint{{Target: "VMInstanceIDs.InstanceIds", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + errChan <- validation.NewErrorWithValidationError(err, "compute.VirtualMachineScaleSetsClient", "UpdateInstances") + close(errChan) + close(resultChan) + return resultChan, errChan + } + + go func() { + var err error + var result OperationStatusResponse + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.UpdateInstancesPreparer(resourceGroupName, VMScaleSetName, VMInstanceIDs, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "UpdateInstances", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateInstancesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "UpdateInstances", resp, "Failure sending request") + return + } + + result, err = client.UpdateInstancesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetsClient", "UpdateInstances", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // UpdateInstancesPreparer prepares the UpdateInstances request. -func (client VirtualMachineScaleSetsClient) UpdateInstancesPreparer(resourceGroupName string, vmScaleSetName string, vmInstanceIDs VirtualMachineScaleSetVMInstanceRequiredIDs, cancel <-chan struct{}) (*http.Request, error) { +func (client VirtualMachineScaleSetsClient) UpdateInstancesPreparer(resourceGroupName string, VMScaleSetName string, VMInstanceIDs VirtualMachineScaleSetVMInstanceRequiredIDs, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -1065,7 +1289,7 @@ func (client VirtualMachineScaleSetsClient) UpdateInstancesPreparer(resourceGrou autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/manualupgrade", pathParameters), - autorest.WithJSON(vmInstanceIDs), + autorest.WithJSON(VMInstanceIDs), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare(&http.Request{Cancel: cancel}) } @@ -1080,12 +1304,13 @@ func (client VirtualMachineScaleSetsClient) UpdateInstancesSender(req *http.Requ // UpdateInstancesResponder handles the response to the UpdateInstances request. The method always // closes the http.Response Body. -func (client VirtualMachineScaleSetsClient) UpdateInstancesResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualMachineScaleSetsClient) UpdateInstancesResponder(resp *http.Response) (result OperationStatusResponse, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{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 old mode 100644 new mode 100755 index f0b309510e63..34e0934dcb68 --- 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,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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -42,46 +42,60 @@ func NewVirtualMachineScaleSetVMsClientWithBaseURI(baseURI string, subscriptionI } // Deallocate deallocates a specific virtual machine in a VM scale set. Shuts -// down the virtual machine and releases the compute resources it uses. You -// are not billed for the compute resources of this virtual machine once it -// is deallocated. 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. +// down the virtual machine and releases the compute resources it uses. You are +// not billed for the compute resources of this virtual machine once it is +// deallocated. 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 +// resourceGroupName is the name of the resource group. VMScaleSetName is the // name of the VM scale set. instanceID is the instance ID of the virtual // machine. -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", nil, "Failure preparing request") - } - - resp, err := client.DeallocateSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Deallocate", resp, "Failure sending request") - } - - result, err = client.DeallocateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Deallocate", resp, "Failure responding to request") - } - - return +func (client VirtualMachineScaleSetVMsClient) Deallocate(resourceGroupName string, VMScaleSetName string, instanceID string, cancel <-chan struct{}) (<-chan OperationStatusResponse, <-chan error) { + resultChan := make(chan OperationStatusResponse, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result OperationStatusResponse + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeallocatePreparer(resourceGroupName, VMScaleSetName, instanceID, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Deallocate", nil, "Failure preparing request") + return + } + + resp, err := client.DeallocateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Deallocate", resp, "Failure sending request") + return + } + + result, err = client.DeallocateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Deallocate", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // DeallocatePreparer prepares the Deallocate request. -func (client VirtualMachineScaleSetVMsClient) DeallocatePreparer(resourceGroupName string, vmScaleSetName string, instanceID string, cancel <-chan struct{}) (*http.Request, error) { +func (client VirtualMachineScaleSetVMsClient) DeallocatePreparer(resourceGroupName string, VMScaleSetName string, instanceID string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -102,13 +116,14 @@ func (client VirtualMachineScaleSetVMsClient) DeallocateSender(req *http.Request // DeallocateResponder handles the response to the Deallocate request. The method always // closes the http.Response Body. -func (client VirtualMachineScaleSetVMsClient) DeallocateResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualMachineScaleSetVMsClient) DeallocateResponder(resp *http.Response) (result OperationStatusResponse, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } @@ -117,40 +132,54 @@ func (client VirtualMachineScaleSetVMsClient) DeallocateResponder(resp *http.Res // 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 +// resourceGroupName is the name of the resource group. VMScaleSetName is the // name of the VM scale set. instanceID is the instance ID of the virtual // machine. -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", nil, "Failure preparing request") - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Delete", resp, "Failure sending request") - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Delete", resp, "Failure responding to request") - } - - return +func (client VirtualMachineScaleSetVMsClient) Delete(resourceGroupName string, VMScaleSetName string, instanceID string, cancel <-chan struct{}) (<-chan OperationStatusResponse, <-chan error) { + resultChan := make(chan OperationStatusResponse, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result OperationStatusResponse + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeletePreparer(resourceGroupName, VMScaleSetName, instanceID, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Delete", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // DeletePreparer prepares the Delete request. -func (client VirtualMachineScaleSetVMsClient) DeletePreparer(resourceGroupName string, vmScaleSetName string, instanceID string, cancel <-chan struct{}) (*http.Request, error) { +func (client VirtualMachineScaleSetVMsClient) DeletePreparer(resourceGroupName string, VMScaleSetName string, instanceID string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -171,31 +200,34 @@ func (client VirtualMachineScaleSetVMsClient) DeleteSender(req *http.Request) (* // DeleteResponder handles the response to the Delete request. The method always // closes the http.Response Body. -func (client VirtualMachineScaleSetVMsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualMachineScaleSetVMsClient) DeleteResponder(resp *http.Response) (result OperationStatusResponse, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } // Get gets a virtual machine from a VM scale set. // -// resourceGroupName is the name of the resource group. vmScaleSetName is the +// resourceGroupName is the name of the resource group. VMScaleSetName is the // name of the VM scale set. instanceID is the instance ID of the virtual // machine. -func (client VirtualMachineScaleSetVMsClient) Get(resourceGroupName string, vmScaleSetName string, instanceID string) (result VirtualMachineScaleSetVM, err error) { - req, err := client.GetPreparer(resourceGroupName, vmScaleSetName, instanceID) +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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Get", nil, "Failure preparing request") + return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Get", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Get", resp, "Failure sending request") + return } result, err = client.GetResponder(resp) @@ -207,16 +239,17 @@ func (client VirtualMachineScaleSetVMsClient) Get(resourceGroupName string, vmSc } // GetPreparer prepares the Get request. -func (client VirtualMachineScaleSetVMsClient) GetPreparer(resourceGroupName string, vmScaleSetName string, instanceID string) (*http.Request, error) { +func (client VirtualMachineScaleSetVMsClient) GetPreparer(resourceGroupName string, VMScaleSetName string, instanceID string) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -248,19 +281,21 @@ func (client VirtualMachineScaleSetVMsClient) GetResponder(resp *http.Response) // GetInstanceView gets the status of a virtual machine from a VM scale set. // -// resourceGroupName is the name of the resource group. vmScaleSetName is the +// resourceGroupName is the name of the resource group. VMScaleSetName is the // name of the VM scale set. instanceID is the instance ID of the virtual // machine. -func (client VirtualMachineScaleSetVMsClient) GetInstanceView(resourceGroupName string, vmScaleSetName string, instanceID string) (result VirtualMachineScaleSetVMInstanceView, err error) { - req, err := client.GetInstanceViewPreparer(resourceGroupName, vmScaleSetName, instanceID) +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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "GetInstanceView", nil, "Failure preparing request") + return } resp, err := client.GetInstanceViewSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "GetInstanceView", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "GetInstanceView", resp, "Failure sending request") + return } result, err = client.GetInstanceViewResponder(resp) @@ -272,16 +307,17 @@ func (client VirtualMachineScaleSetVMsClient) GetInstanceView(resourceGroupName } // GetInstanceViewPreparer prepares the GetInstanceView request. -func (client VirtualMachineScaleSetVMsClient) GetInstanceViewPreparer(resourceGroupName string, vmScaleSetName string, instanceID string) (*http.Request, error) { +func (client VirtualMachineScaleSetVMsClient) GetInstanceViewPreparer(resourceGroupName string, VMScaleSetName string, instanceID string) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -320,13 +356,15 @@ func (client VirtualMachineScaleSetVMsClient) GetInstanceViewResponder(resp *htt 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "List", nil, "Failure preparing request") + return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "List", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "List", resp, "Failure sending request") + return } result, err = client.ListResponder(resp) @@ -345,8 +383,9 @@ func (client VirtualMachineScaleSetVMsClient) ListPreparer(resourceGroupName str "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } if len(filter) > 0 { queryParameters["$filter"] = autorest.Encode("query", filter) @@ -410,46 +449,60 @@ func (client VirtualMachineScaleSetVMsClient) ListNextResults(lastResults Virtua } // PowerOff power off (stop) a virtual machine in a VM scale set. Note that -// resources are still attached and you are getting charged for the -// resources. Instead, use deallocate to release resources and avoid charges. -// 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. +// resources are still attached and you are getting charged for the resources. +// Instead, use deallocate to release resources and avoid charges. 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 +// resourceGroupName is the name of the resource group. VMScaleSetName is the // name of the VM scale set. instanceID is the instance ID of the virtual // machine. -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", nil, "Failure preparing request") - } - - resp, err := client.PowerOffSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "PowerOff", resp, "Failure sending request") - } - - result, err = client.PowerOffResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "PowerOff", resp, "Failure responding to request") - } - - return +func (client VirtualMachineScaleSetVMsClient) PowerOff(resourceGroupName string, VMScaleSetName string, instanceID string, cancel <-chan struct{}) (<-chan OperationStatusResponse, <-chan error) { + resultChan := make(chan OperationStatusResponse, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result OperationStatusResponse + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.PowerOffPreparer(resourceGroupName, VMScaleSetName, instanceID, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "PowerOff", nil, "Failure preparing request") + return + } + + resp, err := client.PowerOffSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "PowerOff", resp, "Failure sending request") + return + } + + result, err = client.PowerOffResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "PowerOff", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // PowerOffPreparer prepares the PowerOff request. -func (client VirtualMachineScaleSetVMsClient) PowerOffPreparer(resourceGroupName string, vmScaleSetName string, instanceID string, cancel <-chan struct{}) (*http.Request, error) { +func (client VirtualMachineScaleSetVMsClient) PowerOffPreparer(resourceGroupName string, VMScaleSetName string, instanceID string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -470,55 +523,70 @@ func (client VirtualMachineScaleSetVMsClient) PowerOffSender(req *http.Request) // PowerOffResponder handles the response to the PowerOff request. The method always // closes the http.Response Body. -func (client VirtualMachineScaleSetVMsClient) PowerOffResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualMachineScaleSetVMsClient) PowerOffResponder(resp *http.Response) (result OperationStatusResponse, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } // Reimage reimages (upgrade the operating system) a specific virtual machine // in a VM 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. +// 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 +// resourceGroupName is the name of the resource group. VMScaleSetName is the // name of the VM scale set. instanceID is the instance ID of the virtual // machine. -func (client VirtualMachineScaleSetVMsClient) Reimage(resourceGroupName string, vmScaleSetName string, instanceID string, cancel <-chan struct{}) (result autorest.Response, err error) { - req, err := client.ReimagePreparer(resourceGroupName, vmScaleSetName, instanceID, cancel) - if err != nil { - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Reimage", nil, "Failure preparing request") - } - - resp, err := client.ReimageSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Reimage", resp, "Failure sending request") - } - - result, err = client.ReimageResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Reimage", resp, "Failure responding to request") - } - - return +func (client VirtualMachineScaleSetVMsClient) Reimage(resourceGroupName string, VMScaleSetName string, instanceID string, cancel <-chan struct{}) (<-chan OperationStatusResponse, <-chan error) { + resultChan := make(chan OperationStatusResponse, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result OperationStatusResponse + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.ReimagePreparer(resourceGroupName, VMScaleSetName, instanceID, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Reimage", nil, "Failure preparing request") + return + } + + resp, err := client.ReimageSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Reimage", resp, "Failure sending request") + return + } + + result, err = client.ReimageResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Reimage", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // ReimagePreparer prepares the Reimage request. -func (client VirtualMachineScaleSetVMsClient) ReimagePreparer(resourceGroupName string, vmScaleSetName string, instanceID string, cancel <-chan struct{}) (*http.Request, error) { +func (client VirtualMachineScaleSetVMsClient) ReimagePreparer(resourceGroupName string, VMScaleSetName string, instanceID string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -539,55 +607,155 @@ func (client VirtualMachineScaleSetVMsClient) ReimageSender(req *http.Request) ( // ReimageResponder handles the response to the Reimage request. The method always // closes the http.Response Body. -func (client VirtualMachineScaleSetVMsClient) ReimageResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualMachineScaleSetVMsClient) ReimageResponder(resp *http.Response) (result OperationStatusResponse, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } -// Restart restarts a virtual machine in a VM 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. +// ReimageAll allows you to re-image all the disks ( including data disks ) in +// the a virtual machine scale set instance. This operation is only supported +// for managed disks. 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 +// resourceGroupName is the name of the resource group. VMScaleSetName is the // name of the VM scale set. instanceID is the instance ID of the virtual // machine. -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", nil, "Failure preparing request") +func (client VirtualMachineScaleSetVMsClient) ReimageAll(resourceGroupName string, VMScaleSetName string, instanceID string, cancel <-chan struct{}) (<-chan OperationStatusResponse, <-chan error) { + resultChan := make(chan OperationStatusResponse, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result OperationStatusResponse + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.ReimageAllPreparer(resourceGroupName, VMScaleSetName, instanceID, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "ReimageAll", nil, "Failure preparing request") + return + } + + resp, err := client.ReimageAllSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "ReimageAll", resp, "Failure sending request") + return + } + + result, err = client.ReimageAllResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "ReimageAll", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// ReimageAllPreparer prepares the ReimageAll request. +func (client VirtualMachineScaleSetVMsClient) ReimageAllPreparer(resourceGroupName string, VMScaleSetName string, instanceID string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "instanceId": autorest.Encode("path", instanceID), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } - resp, err := client.RestartSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Restart", resp, "Failure sending request") + const APIVersion = "2016-04-30-preview" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, } - result, err = client.RestartResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Restart", resp, "Failure responding to request") - } + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualmachines/{instanceId}/reimageall", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// ReimageAllSender sends the ReimageAll request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualMachineScaleSetVMsClient) ReimageAllSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} +// ReimageAllResponder handles the response to the ReimageAll request. The method always +// closes the http.Response Body. +func (client VirtualMachineScaleSetVMsClient) ReimageAllResponder(resp *http.Response) (result OperationStatusResponse, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} return } +// Restart restarts a virtual machine in a VM 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 VM scale set. instanceID is the instance ID of the virtual +// machine. +func (client VirtualMachineScaleSetVMsClient) Restart(resourceGroupName string, VMScaleSetName string, instanceID string, cancel <-chan struct{}) (<-chan OperationStatusResponse, <-chan error) { + resultChan := make(chan OperationStatusResponse, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result OperationStatusResponse + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.RestartPreparer(resourceGroupName, VMScaleSetName, instanceID, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Restart", nil, "Failure preparing request") + return + } + + resp, err := client.RestartSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Restart", resp, "Failure sending request") + return + } + + result, err = client.RestartResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Restart", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + // RestartPreparer prepares the Restart request. -func (client VirtualMachineScaleSetVMsClient) RestartPreparer(resourceGroupName string, vmScaleSetName string, instanceID string, cancel <-chan struct{}) (*http.Request, error) { +func (client VirtualMachineScaleSetVMsClient) RestartPreparer(resourceGroupName string, VMScaleSetName string, instanceID string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -608,55 +776,70 @@ func (client VirtualMachineScaleSetVMsClient) RestartSender(req *http.Request) ( // RestartResponder handles the response to the Restart request. The method always // closes the http.Response Body. -func (client VirtualMachineScaleSetVMsClient) RestartResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualMachineScaleSetVMsClient) RestartResponder(resp *http.Response) (result OperationStatusResponse, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } // Start starts a virtual machine in a VM 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. +// 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 +// resourceGroupName is the name of the resource group. VMScaleSetName is the // name of the VM scale set. instanceID is the instance ID of the virtual // machine. -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", nil, "Failure preparing request") - } - - resp, err := client.StartSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Start", resp, "Failure sending request") - } - - result, err = client.StartResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Start", resp, "Failure responding to request") - } - - return +func (client VirtualMachineScaleSetVMsClient) Start(resourceGroupName string, VMScaleSetName string, instanceID string, cancel <-chan struct{}) (<-chan OperationStatusResponse, <-chan error) { + resultChan := make(chan OperationStatusResponse, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result OperationStatusResponse + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.StartPreparer(resourceGroupName, VMScaleSetName, instanceID, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Start", nil, "Failure preparing request") + return + } + + resp, err := client.StartSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Start", resp, "Failure sending request") + return + } + + result, err = client.StartResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "compute.VirtualMachineScaleSetVMsClient", "Start", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // StartPreparer prepares the Start request. -func (client VirtualMachineScaleSetVMsClient) StartPreparer(resourceGroupName string, vmScaleSetName string, instanceID string, cancel <-chan struct{}) (*http.Request, error) { +func (client VirtualMachineScaleSetVMsClient) StartPreparer(resourceGroupName string, VMScaleSetName string, instanceID string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "instanceId": autorest.Encode("path", instanceID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "vmScaleSetName": autorest.Encode("path", vmScaleSetName), + "vmScaleSetName": autorest.Encode("path", VMScaleSetName), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -677,12 +860,13 @@ func (client VirtualMachineScaleSetVMsClient) StartSender(req *http.Request) (*h // StartResponder handles the response to the Start request. The method always // closes the http.Response Body. -func (client VirtualMachineScaleSetVMsClient) StartResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualMachineScaleSetVMsClient) StartResponder(resp *http.Response) (result OperationStatusResponse, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{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 old mode 100644 new mode 100755 index 507e9f157ec4..c76b203e7e9d --- 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,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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -55,13 +55,15 @@ func (client VirtualMachineSizesClient) List(location string) (result VirtualMac req, err := client.ListPreparer(location) if err != nil { - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineSizesClient", "List", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineSizesClient", "List", nil, "Failure preparing request") + return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "compute.VirtualMachineSizesClient", "List", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "compute.VirtualMachineSizesClient", "List", resp, "Failure sending request") + return } result, err = client.ListResponder(resp) @@ -79,8 +81,9 @@ func (client VirtualMachineSizesClient) ListPreparer(location string) (*http.Req "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2016-04-30-preview" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/containerregistry/BUILD b/vendor/github.com/Azure/azure-sdk-for-go/arm/containerregistry/BUILD index ca72cd91d008..92c50e6bcc41 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/containerregistry/BUILD +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/containerregistry/BUILD @@ -12,6 +12,7 @@ go_library( srcs = [ "client.go", "models.go", + "operations.go", "registries.go", "version.go", ], diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/containerregistry/client.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/containerregistry/client.go old mode 100644 new mode 100755 index 2257c451fb11..e5e99db676c3 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/containerregistry/client.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/containerregistry/client.go @@ -1,5 +1,6 @@ -// Package containerregistry implements the Azure ARM Containerregistry -// service API version 2016-06-27-preview. +// Package containerregistry implements the Azure ARM Containerregistry service +// API version 2017-03-01. +// // package containerregistry @@ -17,7 +18,7 @@ package containerregistry // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -26,9 +27,6 @@ import ( ) const ( - // APIVersion is the version of the Containerregistry - APIVersion = "2016-06-27-preview" - // DefaultBaseURI is the default URI used for the service Containerregistry DefaultBaseURI = "https://management.azure.com" ) @@ -37,7 +35,6 @@ const ( type ManagementClient struct { autorest.Client BaseURI string - APIVersion string SubscriptionID string } @@ -51,7 +48,6 @@ func NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient { return ManagementClient{ Client: autorest.NewClientWithUserAgent(UserAgent()), BaseURI: baseURI, - APIVersion: APIVersion, SubscriptionID: subscriptionID, } } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/containerregistry/models.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/containerregistry/models.go old mode 100644 new mode 100755 index ecf1ca8f648e..66edd68c5694 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/containerregistry/models.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/containerregistry/models.go @@ -14,7 +14,7 @@ package containerregistry // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -25,6 +25,75 @@ import ( "net/http" ) +// PasswordName enumerates the values for password name. +type PasswordName string + +const ( + // Password specifies the password state for password name. + Password PasswordName = "password" + // Password2 specifies the password 2 state for password name. + Password2 PasswordName = "password2" +) + +// ProvisioningState enumerates the values for provisioning state. +type ProvisioningState string + +const ( + // Creating specifies the creating state for provisioning state. + Creating ProvisioningState = "Creating" + // Succeeded specifies the succeeded state for provisioning state. + Succeeded ProvisioningState = "Succeeded" +) + +// SkuTier enumerates the values for sku tier. +type SkuTier string + +const ( + // Basic specifies the basic state for sku tier. + Basic SkuTier = "Basic" +) + +// OperationDefinition is the definition of a container registry operation. +type OperationDefinition struct { + Name *string `json:"name,omitempty"` + Display *OperationDisplayDefinition `json:"display,omitempty"` +} + +// OperationDisplayDefinition is the display information for a container +// registry operation. +type OperationDisplayDefinition struct { + Provider *string `json:"provider,omitempty"` + Resource *string `json:"resource,omitempty"` + Operation *string `json:"operation,omitempty"` + Description *string `json:"description,omitempty"` +} + +// OperationListResult is the result of a request to list container registry +// operations. +type OperationListResult struct { + autorest.Response `json:"-"` + Value *[]OperationDefinition `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// OperationListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client OperationListResult) OperationListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// RegenerateCredentialParameters is the parameters used to regenerate the +// login credential. +type RegenerateCredentialParameters struct { + Name PasswordName `json:"name,omitempty"` +} + // Registry is an object that represents a container registry. type Registry struct { autorest.Response `json:"-"` @@ -33,15 +102,25 @@ type Registry struct { Type *string `json:"type,omitempty"` Location *string `json:"location,omitempty"` Tags *map[string]*string `json:"tags,omitempty"` + Sku *Sku `json:"sku,omitempty"` *RegistryProperties `json:"properties,omitempty"` } -// RegistryCredentials is the result of a request to get the administrator -// login credentials for a container registry. -type RegistryCredentials struct { +// RegistryCreateParameters is the parameters for creating a container +// registry. +type RegistryCreateParameters struct { + Tags *map[string]*string `json:"tags,omitempty"` + Location *string `json:"location,omitempty"` + Sku *Sku `json:"sku,omitempty"` + *RegistryPropertiesCreateParameters `json:"properties,omitempty"` +} + +// RegistryListCredentialsResult is the response from the ListCredentials +// operation. +type RegistryListCredentialsResult struct { autorest.Response `json:"-"` - Username *string `json:"username,omitempty"` - Password *string `json:"password,omitempty"` + Username *string `json:"username,omitempty"` + Passwords *[]RegistryPassword `json:"passwords,omitempty"` } // RegistryListResult is the result of a request to list container registries. @@ -63,15 +142,15 @@ func (client RegistryListResult) RegistryListResultPreparer() (*http.Request, er autorest.WithBaseURL(to.String(client.NextLink))) } -// RegistryNameCheckRequest is a request to check whether the container -// registry name is available. +// RegistryNameCheckRequest is a request to check whether a container registry +// name is available. type RegistryNameCheckRequest struct { Name *string `json:"name,omitempty"` Type *string `json:"type,omitempty"` } -// RegistryNameStatus is the result of a request to check the availability of -// a container registry name. +// RegistryNameStatus is the result of a request to check the availability of a +// container registry name. type RegistryNameStatus struct { autorest.Response `json:"-"` NameAvailable *bool `json:"nameAvailable,omitempty"` @@ -79,19 +158,33 @@ type RegistryNameStatus struct { Message *string `json:"message,omitempty"` } +// RegistryPassword is the login password for the container registry. +type RegistryPassword struct { + Name PasswordName `json:"name,omitempty"` + Value *string `json:"value,omitempty"` +} + // RegistryProperties is the properties of a container registry. type RegistryProperties struct { - LoginServer *string `json:"loginServer,omitempty"` - CreationDate *date.Time `json:"creationDate,omitempty"` + LoginServer *string `json:"loginServer,omitempty"` + CreationDate *date.Time `json:"creationDate,omitempty"` + ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` + AdminUserEnabled *bool `json:"adminUserEnabled,omitempty"` + StorageAccount *StorageAccountProperties `json:"storageAccount,omitempty"` +} + +// RegistryPropertiesCreateParameters is the parameters for creating the +// properties of a container registry. +type RegistryPropertiesCreateParameters struct { AdminUserEnabled *bool `json:"adminUserEnabled,omitempty"` - StorageAccount *StorageAccountProperties `json:"storageAccount,omitempty"` + StorageAccount *StorageAccountParameters `json:"storageAccount,omitempty"` } // RegistryPropertiesUpdateParameters is the parameters for updating the // properties of a container registry. type RegistryPropertiesUpdateParameters struct { AdminUserEnabled *bool `json:"adminUserEnabled,omitempty"` - StorageAccount *StorageAccountProperties `json:"storageAccount,omitempty"` + StorageAccount *StorageAccountParameters `json:"storageAccount,omitempty"` } // RegistryUpdateParameters is the parameters for updating a container @@ -110,9 +203,21 @@ type Resource struct { Tags *map[string]*string `json:"tags,omitempty"` } -// StorageAccountProperties is the properties of a storage account for a +// Sku is the SKU of a container registry. +type Sku struct { + Name *string `json:"name,omitempty"` + Tier SkuTier `json:"tier,omitempty"` +} + +// StorageAccountParameters is the parameters of a storage account for a // container registry. -type StorageAccountProperties struct { +type StorageAccountParameters struct { Name *string `json:"name,omitempty"` AccessKey *string `json:"accessKey,omitempty"` } + +// StorageAccountProperties is the properties of a storage account for a +// container registry. +type StorageAccountProperties struct { + Name *string `json:"name,omitempty"` +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/containerregistry/operations.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/containerregistry/operations.go new file mode 100755 index 000000000000..a1694180c5fb --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/containerregistry/operations.go @@ -0,0 +1,124 @@ +package containerregistry + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// OperationsClient is the client for the Operations methods of the +// Containerregistry service. +type OperationsClient struct { + ManagementClient +} + +// NewOperationsClient creates an instance of the OperationsClient client. +func NewOperationsClient(subscriptionID string) OperationsClient { + return NewOperationsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewOperationsClientWithBaseURI creates an instance of the OperationsClient +// client. +func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient { + return OperationsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// List lists all of the available Azure Container Registry REST API +// operations. +func (client OperationsClient) List() (result OperationListResult, err error) { + req, err := client.ListPreparer() + if err != nil { + err = autorest.NewErrorWithError(err, "containerregistry.OperationsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "containerregistry.OperationsClient", "List", resp, "Failure sending request") + return + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "containerregistry.OperationsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client OperationsClient) ListPreparer() (*http.Request, error) { + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPath("/providers/Microsoft.ContainerRegistry/operations"), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client OperationsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client OperationsClient) ListResponder(resp *http.Response) (result OperationListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListNextResults retrieves the next set of results, if any. +func (client OperationsClient) ListNextResults(lastResults OperationListResult) (result OperationListResult, err error) { + req, err := lastResults.OperationListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "containerregistry.OperationsClient", "List", nil, "Failure preparing next results request") + } + if req == nil { + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "containerregistry.OperationsClient", "List", resp, "Failure sending next results request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "containerregistry.OperationsClient", "List", resp, "Failure responding to next results request") + } + + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/containerregistry/registries.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/containerregistry/registries.go old mode 100644 new mode 100755 index c658cccf580b..fe03ba33818e --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/containerregistry/registries.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/containerregistry/registries.go @@ -14,7 +14,7 @@ package containerregistry // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -51,20 +51,26 @@ func NewRegistriesClientWithBaseURI(baseURI string, subscriptionID string) Regis func (client RegistriesClient) CheckNameAvailability(registryNameCheckRequest RegistryNameCheckRequest) (result RegistryNameStatus, err error) { if err := validation.Validate([]validation.Validation{ {TargetValue: registryNameCheckRequest, - Constraints: []validation.Constraint{{Target: "registryNameCheckRequest.Name", Name: validation.Null, Rule: true, Chain: nil}, + Constraints: []validation.Constraint{{Target: "registryNameCheckRequest.Name", Name: validation.Null, Rule: true, + Chain: []validation.Constraint{{Target: "registryNameCheckRequest.Name", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "registryNameCheckRequest.Name", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "registryNameCheckRequest.Name", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]*$`, Chain: nil}, + }}, {Target: "registryNameCheckRequest.Type", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { return result, validation.NewErrorWithValidationError(err, "containerregistry.RegistriesClient", "CheckNameAvailability") } req, err := client.CheckNameAvailabilityPreparer(registryNameCheckRequest) if err != nil { - return result, autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "CheckNameAvailability", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "CheckNameAvailability", nil, "Failure preparing request") + return } resp, err := client.CheckNameAvailabilitySender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "CheckNameAvailability", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "CheckNameAvailability", resp, "Failure sending request") + return } result, err = client.CheckNameAvailabilityResponder(resp) @@ -81,8 +87,9 @@ func (client RegistriesClient) CheckNameAvailabilityPreparer(registryNameCheckRe "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -114,55 +121,80 @@ func (client RegistriesClient) CheckNameAvailabilityResponder(resp *http.Respons return } -// CreateOrUpdate creates or updates a container registry with the specified -// parameters. +// Create creates a container registry with the specified parameters. 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 which the container // registry belongs. registryName is the name of the container registry. -// registry is the parameters for creating or updating a container registry. -func (client RegistriesClient) CreateOrUpdate(resourceGroupName string, registryName string, registry Registry) (result Registry, err error) { +// registryCreateParameters is the parameters for creating a container +// registry. +func (client RegistriesClient) Create(resourceGroupName string, registryName string, registryCreateParameters RegistryCreateParameters, cancel <-chan struct{}) (<-chan Registry, <-chan error) { + resultChan := make(chan Registry, 1) + errChan := make(chan error, 1) if err := validation.Validate([]validation.Validation{ - {TargetValue: registry, - Constraints: []validation.Constraint{{Target: "registry.RegistryProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "registry.RegistryProperties.StorageAccount", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "registry.RegistryProperties.StorageAccount.Name", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "registry.RegistryProperties.StorageAccount.AccessKey", Name: validation.Null, Rule: true, Chain: nil}, - }}, - {Target: "registry.RegistryProperties.LoginServer", Name: validation.ReadOnly, Rule: true, Chain: nil}, - {Target: "registry.RegistryProperties.CreationDate", Name: validation.ReadOnly, Rule: true, Chain: nil}, - }}}}}); err != nil { - return result, validation.NewErrorWithValidationError(err, "containerregistry.RegistriesClient", "CreateOrUpdate") - } - - req, err := client.CreateOrUpdatePreparer(resourceGroupName, registryName, registry) - if err != nil { - return result, autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "CreateOrUpdate", nil, "Failure preparing request") - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "CreateOrUpdate", resp, "Failure sending request") - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "CreateOrUpdate", resp, "Failure responding to request") - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client RegistriesClient) CreateOrUpdatePreparer(resourceGroupName string, registryName string, registry Registry) (*http.Request, error) { + {TargetValue: registryName, + Constraints: []validation.Constraint{{Target: "registryName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "registryName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "registryName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]*$`, Chain: nil}}}, + {TargetValue: registryCreateParameters, + Constraints: []validation.Constraint{{Target: "registryCreateParameters.Location", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "registryCreateParameters.Sku", Name: validation.Null, Rule: true, + Chain: []validation.Constraint{{Target: "registryCreateParameters.Sku.Name", Name: validation.Null, Rule: true, Chain: nil}}}, + {Target: "registryCreateParameters.RegistryPropertiesCreateParameters", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "registryCreateParameters.RegistryPropertiesCreateParameters.StorageAccount", Name: validation.Null, Rule: true, + Chain: []validation.Constraint{{Target: "registryCreateParameters.RegistryPropertiesCreateParameters.StorageAccount.Name", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "registryCreateParameters.RegistryPropertiesCreateParameters.StorageAccount.AccessKey", Name: validation.Null, Rule: true, Chain: nil}, + }}, + }}}}}); err != nil { + errChan <- validation.NewErrorWithValidationError(err, "containerregistry.RegistriesClient", "Create") + close(errChan) + close(resultChan) + return resultChan, errChan + } + + go func() { + var err error + var result Registry + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.CreatePreparer(resourceGroupName, registryName, registryCreateParameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "Create", nil, "Failure preparing request") + return + } + + resp, err := client.CreateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "Create", resp, "Failure sending request") + return + } + + result, err = client.CreateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "Create", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// CreatePreparer prepares the Create request. +func (client RegistriesClient) CreatePreparer(resourceGroupName string, registryName string, registryCreateParameters RegistryCreateParameters, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ "registryName": autorest.Encode("path", registryName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -170,24 +202,26 @@ func (client RegistriesClient) CreateOrUpdatePreparer(resourceGroupName string, autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}", pathParameters), - autorest.WithJSON(registry), + autorest.WithJSON(registryCreateParameters), autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare(&http.Request{}) + return preparer.Prepare(&http.Request{Cancel: cancel}) } -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// CreateSender sends the Create request. The method will close the // http.Response Body if it receives an error. -func (client RegistriesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req) +func (client RegistriesClient) CreateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) } -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// CreateResponder handles the response to the Create request. The method always // closes the http.Response Body. -func (client RegistriesClient) CreateOrUpdateResponder(resp *http.Response) (result Registry, err error) { +func (client RegistriesClient) CreateResponder(resp *http.Response) (result Registry, err error) { err = autorest.Respond( resp, client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} @@ -199,15 +233,25 @@ func (client RegistriesClient) CreateOrUpdateResponder(resp *http.Response) (res // resourceGroupName is the name of the resource group to which the container // registry belongs. registryName is the name of the container registry. func (client RegistriesClient) Delete(resourceGroupName string, registryName string) (result autorest.Response, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: registryName, + Constraints: []validation.Constraint{{Target: "registryName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "registryName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "registryName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]*$`, Chain: nil}}}}); err != nil { + return result, validation.NewErrorWithValidationError(err, "containerregistry.RegistriesClient", "Delete") + } + req, err := client.DeletePreparer(resourceGroupName, registryName) if err != nil { - return result, autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "Delete", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "Delete", nil, "Failure preparing request") + return } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "Delete", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "Delete", resp, "Failure sending request") + return } result, err = client.DeleteResponder(resp) @@ -226,8 +270,9 @@ func (client RegistriesClient) DeletePreparer(resourceGroupName string, registry "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -250,110 +295,57 @@ func (client RegistriesClient) DeleteResponder(resp *http.Response) (result auto err = autorest.Respond( resp, client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return } -// GetCredentials gets the administrator login credentials for the specified -// container registry. +// Get gets the properties of the specified container registry. // // resourceGroupName is the name of the resource group to which the container // registry belongs. registryName is the name of the container registry. -func (client RegistriesClient) GetCredentials(resourceGroupName string, registryName string) (result RegistryCredentials, err error) { - req, err := client.GetCredentialsPreparer(resourceGroupName, registryName) - if err != nil { - return result, autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "GetCredentials", nil, "Failure preparing request") - } - - resp, err := client.GetCredentialsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "GetCredentials", resp, "Failure sending request") - } - - result, err = client.GetCredentialsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "GetCredentials", resp, "Failure responding to request") - } - - return -} - -// GetCredentialsPreparer prepares the GetCredentials request. -func (client RegistriesClient) GetCredentialsPreparer(resourceGroupName string, registryName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "registryName": autorest.Encode("path", registryName), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, +func (client RegistriesClient) Get(resourceGroupName string, registryName string) (result Registry, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: registryName, + Constraints: []validation.Constraint{{Target: "registryName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "registryName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "registryName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]*$`, Chain: nil}}}}); err != nil { + return result, validation.NewErrorWithValidationError(err, "containerregistry.RegistriesClient", "Get") } - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/getCredentials", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare(&http.Request{}) -} - -// GetCredentialsSender sends the GetCredentials request. The method will close the -// http.Response Body if it receives an error. -func (client RegistriesClient) GetCredentialsSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req) -} - -// GetCredentialsResponder handles the response to the GetCredentials request. The method always -// closes the http.Response Body. -func (client RegistriesClient) GetCredentialsResponder(resp *http.Response) (result RegistryCredentials, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetProperties gets the properties of the specified container registry. -// -// resourceGroupName is the name of the resource group to which the container -// registry belongs. registryName is the name of the container registry. -func (client RegistriesClient) GetProperties(resourceGroupName string, registryName string) (result Registry, err error) { - req, err := client.GetPropertiesPreparer(resourceGroupName, registryName) + req, err := client.GetPreparer(resourceGroupName, registryName) if err != nil { - return result, autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "GetProperties", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "Get", nil, "Failure preparing request") + return } - resp, err := client.GetPropertiesSender(req) + resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "GetProperties", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "Get", resp, "Failure sending request") + return } - result, err = client.GetPropertiesResponder(resp) + result, err = client.GetResponder(resp) if err != nil { - err = autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "GetProperties", resp, "Failure responding to request") + err = autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "Get", resp, "Failure responding to request") } return } -// GetPropertiesPreparer prepares the GetProperties request. -func (client RegistriesClient) GetPropertiesPreparer(resourceGroupName string, registryName string) (*http.Request, error) { +// GetPreparer prepares the Get request. +func (client RegistriesClient) GetPreparer(resourceGroupName string, registryName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "registryName": autorest.Encode("path", registryName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -364,15 +356,15 @@ func (client RegistriesClient) GetPropertiesPreparer(resourceGroupName string, r return preparer.Prepare(&http.Request{}) } -// GetPropertiesSender sends the GetProperties request. The method will close the +// GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. -func (client RegistriesClient) GetPropertiesSender(req *http.Request) (*http.Response, error) { +func (client RegistriesClient) GetSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req) } -// GetPropertiesResponder handles the response to the GetProperties request. The method always +// GetResponder handles the response to the Get request. The method always // closes the http.Response Body. -func (client RegistriesClient) GetPropertiesResponder(resp *http.Response) (result Registry, err error) { +func (client RegistriesClient) GetResponder(resp *http.Response) (result Registry, err error) { err = autorest.Respond( resp, client.ByInspecting(), @@ -383,18 +375,19 @@ func (client RegistriesClient) GetPropertiesResponder(resp *http.Response) (resu return } -// List lists all the available container registries under the specified -// subscription. +// List lists all the container registries under the specified subscription. func (client RegistriesClient) List() (result RegistryListResult, err error) { req, err := client.ListPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "List", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "List", nil, "Failure preparing request") + return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "List", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "List", resp, "Failure sending request") + return } result, err = client.ListResponder(resp) @@ -411,8 +404,9 @@ func (client RegistriesClient) ListPreparer() (*http.Request, error) { "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -466,21 +460,23 @@ func (client RegistriesClient) ListNextResults(lastResults RegistryListResult) ( return } -// ListByResourceGroup lists all the available container registries under the -// specified resource group. +// ListByResourceGroup lists all the container registries under the specified +// resource group. // // resourceGroupName is the name of the resource group to which the container // registry belongs. func (client RegistriesClient) ListByResourceGroup(resourceGroupName string) (result RegistryListResult, err error) { req, err := client.ListByResourceGroupPreparer(resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "ListByResourceGroup", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "ListByResourceGroup", nil, "Failure preparing request") + return } resp, err := client.ListByResourceGroupSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "ListByResourceGroup", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "ListByResourceGroup", resp, "Failure sending request") + return } result, err = client.ListByResourceGroupResponder(resp) @@ -498,8 +494,9 @@ func (client RegistriesClient) ListByResourceGroupPreparer(resourceGroupName str "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -553,60 +550,150 @@ func (client RegistriesClient) ListByResourceGroupNextResults(lastResults Regist return } -// RegenerateCredentials regenerates the administrator login credentials for -// the specified container registry. +// ListCredentials lists the login credentials for the specified container +// registry. +// +// resourceGroupName is the name of the resource group to which the container +// registry belongs. registryName is the name of the container registry. +func (client RegistriesClient) ListCredentials(resourceGroupName string, registryName string) (result RegistryListCredentialsResult, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: registryName, + Constraints: []validation.Constraint{{Target: "registryName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "registryName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "registryName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]*$`, Chain: nil}}}}); err != nil { + return result, validation.NewErrorWithValidationError(err, "containerregistry.RegistriesClient", "ListCredentials") + } + + req, err := client.ListCredentialsPreparer(resourceGroupName, registryName) + if err != nil { + err = autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "ListCredentials", nil, "Failure preparing request") + return + } + + resp, err := client.ListCredentialsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "ListCredentials", resp, "Failure sending request") + return + } + + result, err = client.ListCredentialsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "ListCredentials", resp, "Failure responding to request") + } + + return +} + +// ListCredentialsPreparer prepares the ListCredentials request. +func (client RegistriesClient) ListCredentialsPreparer(resourceGroupName string, registryName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "registryName": autorest.Encode("path", registryName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/listCredentials", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListCredentialsSender sends the ListCredentials request. The method will close the +// http.Response Body if it receives an error. +func (client RegistriesClient) ListCredentialsSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListCredentialsResponder handles the response to the ListCredentials request. The method always +// closes the http.Response Body. +func (client RegistriesClient) ListCredentialsResponder(resp *http.Response) (result RegistryListCredentialsResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// RegenerateCredential regenerates one of the login credentials for the +// specified container registry. // // resourceGroupName is the name of the resource group to which the container // registry belongs. registryName is the name of the container registry. -func (client RegistriesClient) RegenerateCredentials(resourceGroupName string, registryName string) (result RegistryCredentials, err error) { - req, err := client.RegenerateCredentialsPreparer(resourceGroupName, registryName) +// regenerateCredentialParameters is specifies name of the password which +// should be regenerated -- password or password2. +func (client RegistriesClient) RegenerateCredential(resourceGroupName string, registryName string, regenerateCredentialParameters RegenerateCredentialParameters) (result RegistryListCredentialsResult, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: registryName, + Constraints: []validation.Constraint{{Target: "registryName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "registryName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "registryName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]*$`, Chain: nil}}}}); err != nil { + return result, validation.NewErrorWithValidationError(err, "containerregistry.RegistriesClient", "RegenerateCredential") + } + + req, err := client.RegenerateCredentialPreparer(resourceGroupName, registryName, regenerateCredentialParameters) if err != nil { - return result, autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "RegenerateCredentials", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "RegenerateCredential", nil, "Failure preparing request") + return } - resp, err := client.RegenerateCredentialsSender(req) + resp, err := client.RegenerateCredentialSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "RegenerateCredentials", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "RegenerateCredential", resp, "Failure sending request") + return } - result, err = client.RegenerateCredentialsResponder(resp) + result, err = client.RegenerateCredentialResponder(resp) if err != nil { - err = autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "RegenerateCredentials", resp, "Failure responding to request") + err = autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "RegenerateCredential", resp, "Failure responding to request") } return } -// RegenerateCredentialsPreparer prepares the RegenerateCredentials request. -func (client RegistriesClient) RegenerateCredentialsPreparer(resourceGroupName string, registryName string) (*http.Request, error) { +// RegenerateCredentialPreparer prepares the RegenerateCredential request. +func (client RegistriesClient) RegenerateCredentialPreparer(resourceGroupName string, registryName string, regenerateCredentialParameters RegenerateCredentialParameters) (*http.Request, error) { pathParameters := map[string]interface{}{ "registryName": autorest.Encode("path", registryName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( + autorest.AsJSON(), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/regenerateCredentials", pathParameters), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/regenerateCredential", pathParameters), + autorest.WithJSON(regenerateCredentialParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare(&http.Request{}) } -// RegenerateCredentialsSender sends the RegenerateCredentials request. The method will close the +// RegenerateCredentialSender sends the RegenerateCredential request. The method will close the // http.Response Body if it receives an error. -func (client RegistriesClient) RegenerateCredentialsSender(req *http.Request) (*http.Response, error) { +func (client RegistriesClient) RegenerateCredentialSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req) } -// RegenerateCredentialsResponder handles the response to the RegenerateCredentials request. The method always +// RegenerateCredentialResponder handles the response to the RegenerateCredential request. The method always // closes the http.Response Body. -func (client RegistriesClient) RegenerateCredentialsResponder(resp *http.Response) (result RegistryCredentials, err error) { +func (client RegistriesClient) RegenerateCredentialResponder(resp *http.Response) (result RegistryListCredentialsResult, err error) { err = autorest.Respond( resp, client.ByInspecting(), @@ -624,15 +711,25 @@ func (client RegistriesClient) RegenerateCredentialsResponder(resp *http.Respons // registryUpdateParameters is the parameters for updating a container // registry. func (client RegistriesClient) Update(resourceGroupName string, registryName string, registryUpdateParameters RegistryUpdateParameters) (result Registry, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: registryName, + Constraints: []validation.Constraint{{Target: "registryName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "registryName", Name: validation.MinLength, Rule: 5, Chain: nil}, + {Target: "registryName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9]*$`, Chain: nil}}}}); err != nil { + return result, validation.NewErrorWithValidationError(err, "containerregistry.RegistriesClient", "Update") + } + req, err := client.UpdatePreparer(resourceGroupName, registryName, registryUpdateParameters) if err != nil { - return result, autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "Update", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "Update", nil, "Failure preparing request") + return } resp, err := client.UpdateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "Update", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "containerregistry.RegistriesClient", "Update", resp, "Failure sending request") + return } result, err = client.UpdateResponder(resp) @@ -651,8 +748,9 @@ func (client RegistriesClient) UpdatePreparer(resourceGroupName string, registry "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/containerregistry/version.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/containerregistry/version.go old mode 100644 new mode 100755 index e0d70c1b510c..e586a01ce796 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/containerregistry/version.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/containerregistry/version.go @@ -14,30 +14,16 @@ package containerregistry // See the License for the specific language governing permissions and // limitations under the License. // -// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. -import ( - "fmt" -) - -const ( - major = "7" - minor = "0" - 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 arm-%s/%s" -) - // UserAgent returns the UserAgent string to use when sending http.Requests. func UserAgent() string { - return fmt.Sprintf(userAgentFormat, Version(), "containerregistry", "2016-06-27-preview") + return "Azure-SDK-For-Go/v10.0.2-beta arm-containerregistry/2017-03-01" } // Version returns the semantic version (see http://semver.org) of the client. func Version() string { - return fmt.Sprintf(semVerFormat, major, minor, patch, tag) + return "v10.0.2-beta" } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/BUILD b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/BUILD index 6aa185352b59..1c6bfc06fb58 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/BUILD +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/BUILD @@ -11,6 +11,7 @@ go_library( name = "go_default_library", srcs = [ "applicationgateways.go", + "bgpservicecommunities.go", "client.go", "expressroutecircuitauthorizations.go", "expressroutecircuitpeerings.go", @@ -20,7 +21,10 @@ go_library( "loadbalancers.go", "localnetworkgateways.go", "models.go", + "packetcaptures.go", "publicipaddresses.go", + "routefilterrules.go", + "routefilters.go", "routes.go", "routetables.go", "securitygroups.go", @@ -32,11 +36,13 @@ go_library( "virtualnetworkgateways.go", "virtualnetworkpeerings.go", "virtualnetworks.go", + "watchers.go", ], tags = ["automanaged"], deps = [ "//vendor/github.com/Azure/go-autorest/autorest:go_default_library", "//vendor/github.com/Azure/go-autorest/autorest/azure:go_default_library", + "//vendor/github.com/Azure/go-autorest/autorest/date:go_default_library", "//vendor/github.com/Azure/go-autorest/autorest/to:go_default_library", "//vendor/github.com/Azure/go-autorest/autorest/validation:go_default_library", ], 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 old mode 100644 new mode 100755 index 872fbbf7c5b3..4ab4e0734905 --- 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,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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -25,11 +25,7 @@ import ( "net/http" ) -// ApplicationGatewaysClient 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 resources. The API has entities -// that capture the relationship between an end user and the Microsoft Azure -// Networks service. +// ApplicationGatewaysClient is the composite Swagger for Network Client type ApplicationGatewaysClient struct { ManagementClient } @@ -48,30 +44,43 @@ func NewApplicationGatewaysClientWithBaseURI(baseURI string, subscriptionID stri // BackendHealth gets the backend health of the specified application gateway // in a 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. +// 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. expand is expands -// BackendAddressPool and BackendHttpSettings referenced in backend health. -func (client ApplicationGatewaysClient) BackendHealth(resourceGroupName string, applicationGatewayName string, expand string, cancel <-chan struct{}) (result autorest.Response, err error) { - req, err := client.BackendHealthPreparer(resourceGroupName, applicationGatewayName, expand, cancel) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "BackendHealth", nil, "Failure preparing request") - } - - resp, err := client.BackendHealthSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "BackendHealth", resp, "Failure sending request") - } - - result, err = client.BackendHealthResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "BackendHealth", resp, "Failure responding to request") - } - - return +// is the name of the application gateway. expand is expands BackendAddressPool +// and BackendHttpSettings referenced in backend health. +func (client ApplicationGatewaysClient) BackendHealth(resourceGroupName string, applicationGatewayName string, expand string, cancel <-chan struct{}) (<-chan ApplicationGatewayBackendHealth, <-chan error) { + resultChan := make(chan ApplicationGatewayBackendHealth, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result ApplicationGatewayBackendHealth + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.BackendHealthPreparer(resourceGroupName, applicationGatewayName, expand, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "BackendHealth", nil, "Failure preparing request") + return + } + + resp, err := client.BackendHealthSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "BackendHealth", resp, "Failure sending request") + return + } + + result, err = client.BackendHealthResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "BackendHealth", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // BackendHealthPreparer prepares the BackendHealth request. @@ -82,8 +91,9 @@ func (client ApplicationGatewaysClient) BackendHealthPreparer(resourceGroupName "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } if len(expand) > 0 { queryParameters["$expand"] = autorest.Encode("query", expand) @@ -107,52 +117,71 @@ func (client ApplicationGatewaysClient) BackendHealthSender(req *http.Request) ( // BackendHealthResponder handles the response to the BackendHealth request. The method always // closes the http.Response Body. -func (client ApplicationGatewaysClient) BackendHealthResponder(resp *http.Response) (result autorest.Response, err error) { +func (client ApplicationGatewaysClient) BackendHealthResponder(resp *http.Response) (result ApplicationGatewayBackendHealth, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } // CreateOrUpdate creates or updates the specified application gateway. 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. +// 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. parameters is parameters supplied -// to the create or update application gateway operation. -func (client ApplicationGatewaysClient) CreateOrUpdate(resourceGroupName string, applicationGatewayName string, parameters ApplicationGateway, cancel <-chan struct{}) (result autorest.Response, err error) { +// is the name of the application gateway. parameters is parameters supplied to +// the create or update application gateway operation. +func (client ApplicationGatewaysClient) CreateOrUpdate(resourceGroupName string, applicationGatewayName string, parameters ApplicationGateway, cancel <-chan struct{}) (<-chan ApplicationGateway, <-chan error) { + resultChan := make(chan ApplicationGateway, 1) + errChan := make(chan error, 1) if err := validation.Validate([]validation.Validation{ {TargetValue: parameters, Constraints: []validation.Constraint{{Target: "parameters.ApplicationGatewayPropertiesFormat", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "parameters.ApplicationGatewayPropertiesFormat.WebApplicationFirewallConfiguration", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.ApplicationGatewayPropertiesFormat.WebApplicationFirewallConfiguration.Enabled", Name: validation.Null, Rule: true, Chain: nil}}}, - {Target: "parameters.ApplicationGatewayPropertiesFormat.OperationalState", Name: validation.ReadOnly, Rule: true, Chain: nil}, + Chain: []validation.Constraint{{Target: "parameters.ApplicationGatewayPropertiesFormat.WebApplicationFirewallConfiguration.Enabled", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.ApplicationGatewayPropertiesFormat.WebApplicationFirewallConfiguration.RuleSetType", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.ApplicationGatewayPropertiesFormat.WebApplicationFirewallConfiguration.RuleSetVersion", Name: validation.Null, Rule: true, Chain: nil}, + }}, }}}}}); err != nil { - return result, validation.NewErrorWithValidationError(err, "network.ApplicationGatewaysClient", "CreateOrUpdate") - } - - req, err := client.CreateOrUpdatePreparer(resourceGroupName, applicationGatewayName, parameters, cancel) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "CreateOrUpdate", nil, "Failure preparing request") - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "CreateOrUpdate", resp, "Failure sending request") - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "CreateOrUpdate", resp, "Failure responding to request") - } - - return + errChan <- validation.NewErrorWithValidationError(err, "network.ApplicationGatewaysClient", "CreateOrUpdate") + close(errChan) + close(resultChan) + return resultChan, errChan + } + + go func() { + var err error + var result ApplicationGateway + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.CreateOrUpdatePreparer(resourceGroupName, applicationGatewayName, parameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "CreateOrUpdate", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. @@ -163,8 +192,9 @@ func (client ApplicationGatewaysClient) CreateOrUpdatePreparer(resourceGroupName "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -187,41 +217,55 @@ func (client ApplicationGatewaysClient) CreateOrUpdateSender(req *http.Request) // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client ApplicationGatewaysClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { +func (client ApplicationGatewaysClient) CreateOrUpdateResponder(resp *http.Response) (result ApplicationGateway, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } // Delete deletes the specified application gateway. 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. +// 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) 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", nil, "Failure preparing request") - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Delete", resp, "Failure sending request") - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Delete", resp, "Failure responding to request") - } - - return +func (client ApplicationGatewaysClient) Delete(resourceGroupName string, applicationGatewayName string, cancel <-chan struct{}) (<-chan autorest.Response, <-chan error) { + resultChan := make(chan autorest.Response, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result autorest.Response + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeletePreparer(resourceGroupName, applicationGatewayName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Delete", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // DeletePreparer prepares the Delete request. @@ -232,8 +276,9 @@ func (client ApplicationGatewaysClient) DeletePreparer(resourceGroupName string, "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -271,13 +316,15 @@ func (client ApplicationGatewaysClient) DeleteResponder(resp *http.Response) (re 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Get", nil, "Failure preparing request") + return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Get", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Get", resp, "Failure sending request") + return } result, err = client.GetResponder(resp) @@ -296,8 +343,9 @@ func (client ApplicationGatewaysClient) GetPreparer(resourceGroupName string, ap "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -333,13 +381,15 @@ func (client ApplicationGatewaysClient) GetResponder(resp *http.Response) (resul 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "List", nil, "Failure preparing request") + return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "List", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "List", resp, "Failure sending request") + return } result, err = client.ListResponder(resp) @@ -357,8 +407,9 @@ func (client ApplicationGatewaysClient) ListPreparer(resourceGroupName string) ( "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -416,13 +467,15 @@ func (client ApplicationGatewaysClient) ListNextResults(lastResults ApplicationG func (client ApplicationGatewaysClient) ListAll() (result ApplicationGatewayListResult, err error) { req, err := client.ListAllPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAll", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAll", nil, "Failure preparing request") + return } resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAll", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAll", resp, "Failure sending request") + return } result, err = client.ListAllResponder(resp) @@ -439,8 +492,9 @@ func (client ApplicationGatewaysClient) ListAllPreparer() (*http.Request, error) "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -494,33 +548,108 @@ func (client ApplicationGatewaysClient) ListAllNextResults(lastResults Applicati return } -// Start starts the specified application gateway. 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, cancel <-chan struct{}) (result autorest.Response, err error) { - req, err := client.StartPreparer(resourceGroupName, applicationGatewayName, cancel) +// ListAvailableWafRuleSets lists all available web application firewall rule +// sets. +func (client ApplicationGatewaysClient) ListAvailableWafRuleSets() (result ApplicationGatewayAvailableWafRuleSetsResult, err error) { + req, err := client.ListAvailableWafRuleSetsPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Start", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAvailableWafRuleSets", nil, "Failure preparing request") + return } - resp, err := client.StartSender(req) + resp, err := client.ListAvailableWafRuleSetsSender(req) if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Start", resp, "Failure sending request") + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAvailableWafRuleSets", resp, "Failure sending request") + return } - result, err = client.StartResponder(resp) + result, err = client.ListAvailableWafRuleSetsResponder(resp) if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Start", resp, "Failure responding to request") + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "ListAvailableWafRuleSets", resp, "Failure responding to request") + } + + return +} + +// ListAvailableWafRuleSetsPreparer prepares the ListAvailableWafRuleSets request. +func (client ApplicationGatewaysClient) ListAvailableWafRuleSetsPreparer() (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, } + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/applicationGatewayAvailableWafRuleSets", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListAvailableWafRuleSetsSender sends the ListAvailableWafRuleSets request. The method will close the +// http.Response Body if it receives an error. +func (client ApplicationGatewaysClient) ListAvailableWafRuleSetsSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListAvailableWafRuleSetsResponder handles the response to the ListAvailableWafRuleSets request. The method always +// closes the http.Response Body. +func (client ApplicationGatewaysClient) ListAvailableWafRuleSetsResponder(resp *http.Response) (result ApplicationGatewayAvailableWafRuleSetsResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} return } +// Start starts the specified application gateway. 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, cancel <-chan struct{}) (<-chan autorest.Response, <-chan error) { + resultChan := make(chan autorest.Response, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result autorest.Response + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.StartPreparer(resourceGroupName, applicationGatewayName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Start", nil, "Failure preparing request") + return + } + + resp, err := client.StartSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Start", resp, "Failure sending request") + return + } + + result, err = client.StartResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Start", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + // StartPreparer prepares the Start request. func (client ApplicationGatewaysClient) StartPreparer(resourceGroupName string, applicationGatewayName string, cancel <-chan struct{}) (*http.Request, error) { pathParameters := map[string]interface{}{ @@ -529,8 +658,9 @@ func (client ApplicationGatewaysClient) StartPreparer(resourceGroupName string, "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -563,29 +693,42 @@ func (client ApplicationGatewaysClient) StartResponder(resp *http.Response) (res // Stop stops the specified application gateway in a 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. +// 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, 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", nil, "Failure preparing request") - } - - resp, err := client.StopSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Stop", resp, "Failure sending request") - } - - result, err = client.StopResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Stop", resp, "Failure responding to request") - } - - return +func (client ApplicationGatewaysClient) Stop(resourceGroupName string, applicationGatewayName string, cancel <-chan struct{}) (<-chan autorest.Response, <-chan error) { + resultChan := make(chan autorest.Response, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result autorest.Response + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.StopPreparer(resourceGroupName, applicationGatewayName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Stop", nil, "Failure preparing request") + return + } + + resp, err := client.StopSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Stop", resp, "Failure sending request") + return + } + + result, err = client.StopResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ApplicationGatewaysClient", "Stop", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // StopPreparer prepares the Stop request. @@ -596,8 +739,9 @@ func (client ApplicationGatewaysClient) StopPreparer(resourceGroupName string, a "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/bgpservicecommunities.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/bgpservicecommunities.go new file mode 100755 index 000000000000..5024f5164965 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/bgpservicecommunities.go @@ -0,0 +1,127 @@ +package network + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// BgpServiceCommunitiesClient is the composite Swagger for Network Client +type BgpServiceCommunitiesClient struct { + ManagementClient +} + +// NewBgpServiceCommunitiesClient creates an instance of the +// BgpServiceCommunitiesClient client. +func NewBgpServiceCommunitiesClient(subscriptionID string) BgpServiceCommunitiesClient { + return NewBgpServiceCommunitiesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewBgpServiceCommunitiesClientWithBaseURI creates an instance of the +// BgpServiceCommunitiesClient client. +func NewBgpServiceCommunitiesClientWithBaseURI(baseURI string, subscriptionID string) BgpServiceCommunitiesClient { + return BgpServiceCommunitiesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// List gets all the available bgp service communities. +func (client BgpServiceCommunitiesClient) List() (result BgpServiceCommunityListResult, err error) { + req, err := client.ListPreparer() + if err != nil { + err = autorest.NewErrorWithError(err, "network.BgpServiceCommunitiesClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.BgpServiceCommunitiesClient", "List", resp, "Failure sending request") + return + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.BgpServiceCommunitiesClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client BgpServiceCommunitiesClient) ListPreparer() (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/bgpServiceCommunities", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client BgpServiceCommunitiesClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client BgpServiceCommunitiesClient) ListResponder(resp *http.Response) (result BgpServiceCommunityListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListNextResults retrieves the next set of results, if any. +func (client BgpServiceCommunitiesClient) ListNextResults(lastResults BgpServiceCommunityListResult) (result BgpServiceCommunityListResult, err error) { + req, err := lastResults.BgpServiceCommunityListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.BgpServiceCommunitiesClient", "List", nil, "Failure preparing next results request") + } + if req == nil { + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.BgpServiceCommunitiesClient", "List", resp, "Failure sending next results request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.BgpServiceCommunitiesClient", "List", resp, "Failure responding to next results request") + } + + 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 old mode 100644 new mode 100755 index 74e3d7e491b7..ec5bf7ced542 --- 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,10 +1,6 @@ -// Package network implements the Azure ARM Network service API version -// 2016-09-01. +// Package network implements the Azure ARM Network service API version . // -// The Microsoft Azure Network management API provides a RESTful set of web -// services that interact with Microsoft Azure Networks service to manage -// your network resources. The API has entities that capture the relationship -// between an end user and the Microsoft Azure Networks service. +// Composite Swagger for Network Client package network // Copyright (c) Microsoft and contributors. All rights reserved. @@ -21,7 +17,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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -32,9 +28,6 @@ import ( ) const ( - // APIVersion is the version of the Network - APIVersion = "2016-09-01" - // DefaultBaseURI is the default URI used for the service Network DefaultBaseURI = "https://management.azure.com" ) @@ -43,7 +36,6 @@ const ( type ManagementClient struct { autorest.Client BaseURI string - APIVersion string SubscriptionID string } @@ -57,7 +49,6 @@ func NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient { return ManagementClient{ Client: autorest.NewClientWithUserAgent(UserAgent()), BaseURI: baseURI, - APIVersion: APIVersion, SubscriptionID: subscriptionID, } } @@ -71,13 +62,15 @@ func NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient { 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.ManagementClient", "CheckDNSNameAvailability", nil, "Failure preparing request") + return } resp, err := client.CheckDNSNameAvailabilitySender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ManagementClient", "CheckDNSNameAvailability", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.ManagementClient", "CheckDNSNameAvailability", resp, "Failure sending request") + return } result, err = client.CheckDNSNameAvailabilityResponder(resp) @@ -95,8 +88,9 @@ func (client ManagementClient) CheckDNSNameAvailabilityPreparer(location string, "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } if len(domainNameLabel) > 0 { queryParameters["domainNameLabel"] = autorest.Encode("query", domainNameLabel) 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 old mode 100644 new mode 100755 index eb0a2a075c2c..feb974fb97ca --- 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,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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -24,11 +24,8 @@ import ( "net/http" ) -// ExpressRouteCircuitAuthorizationsClient 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 resources. The API -// has entities that capture the relationship between an end user and the -// Microsoft Azure Networks service. +// ExpressRouteCircuitAuthorizationsClient is the composite Swagger for Network +// Client type ExpressRouteCircuitAuthorizationsClient struct { ManagementClient } @@ -39,39 +36,52 @@ func NewExpressRouteCircuitAuthorizationsClient(subscriptionID string) ExpressRo return NewExpressRouteCircuitAuthorizationsClientWithBaseURI(DefaultBaseURI, subscriptionID) } -// NewExpressRouteCircuitAuthorizationsClientWithBaseURI creates an instance -// of the ExpressRouteCircuitAuthorizationsClient client. +// NewExpressRouteCircuitAuthorizationsClientWithBaseURI creates an instance of +// the ExpressRouteCircuitAuthorizationsClient client. func NewExpressRouteCircuitAuthorizationsClientWithBaseURI(baseURI string, subscriptionID string) ExpressRouteCircuitAuthorizationsClient { return ExpressRouteCircuitAuthorizationsClient{NewWithBaseURI(baseURI, subscriptionID)} } // CreateOrUpdate creates or updates an authorization in the specified express -// route circuit. 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. +// route circuit. 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 or update express route circuit authorization operation. -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", nil, "Failure preparing request") - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "CreateOrUpdate", resp, "Failure sending request") - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "CreateOrUpdate", resp, "Failure responding to request") - } - - return +// 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 +// or update express route circuit authorization operation. +func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdate(resourceGroupName string, circuitName string, authorizationName string, authorizationParameters ExpressRouteCircuitAuthorization, cancel <-chan struct{}) (<-chan ExpressRouteCircuitAuthorization, <-chan error) { + resultChan := make(chan ExpressRouteCircuitAuthorization, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result ExpressRouteCircuitAuthorization + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.CreateOrUpdatePreparer(resourceGroupName, circuitName, authorizationName, authorizationParameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "CreateOrUpdate", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. @@ -83,8 +93,9 @@ func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdatePreparer(res "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -107,13 +118,14 @@ func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdateSender(req * // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { +func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRouteCircuitAuthorization, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } @@ -122,27 +134,40 @@ func (client ExpressRouteCircuitAuthorizationsClient) CreateOrUpdateResponder(re // 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 +// 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, 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", nil, "Failure preparing request") - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Delete", resp, "Failure sending request") - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Delete", resp, "Failure responding to request") - } - - return +func (client ExpressRouteCircuitAuthorizationsClient) Delete(resourceGroupName string, circuitName string, authorizationName string, cancel <-chan struct{}) (<-chan autorest.Response, <-chan error) { + resultChan := make(chan autorest.Response, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result autorest.Response + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeletePreparer(resourceGroupName, circuitName, authorizationName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Delete", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // DeletePreparer prepares the Delete request. @@ -154,8 +179,9 @@ func (client ExpressRouteCircuitAuthorizationsClient) DeletePreparer(resourceGro "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -189,19 +215,21 @@ func (client ExpressRouteCircuitAuthorizationsClient) DeleteResponder(resp *http // Get gets the specified authorization from the specified express route // circuit. // -// resourceGroupName is the name of the resource group. circuitName is the -// name of the express route circuit. authorizationName is the name of the +// 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, err error) { req, err := client.GetPreparer(resourceGroupName, circuitName, authorizationName) if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Get", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Get", nil, "Failure preparing request") + return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Get", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "Get", resp, "Failure sending request") + return } result, err = client.GetResponder(resp) @@ -221,8 +249,9 @@ func (client ExpressRouteCircuitAuthorizationsClient) GetPreparer(resourceGroupN "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -254,18 +283,20 @@ func (client ExpressRouteCircuitAuthorizationsClient) GetResponder(resp *http.Re // List gets all authorizations in an express route circuit. // -// resourceGroupName is the name of the resource group. circuitName is the -// name of the circuit. +// resourceGroupName is the name of the resource group. circuitName is the name +// of the circuit. 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "List", nil, "Failure preparing request") + return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "List", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitAuthorizationsClient", "List", resp, "Failure sending request") + return } result, err = client.ListResponder(resp) @@ -284,8 +315,9 @@ func (client ExpressRouteCircuitAuthorizationsClient) ListPreparer(resourceGroup "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( 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 old mode 100644 new mode 100755 index a459574b89b7..28b926f24438 --- 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,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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -24,11 +24,8 @@ import ( "net/http" ) -// ExpressRouteCircuitPeeringsClient 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 resources. The API -// has entities that capture the relationship between an end user and the -// Microsoft Azure Networks service. +// ExpressRouteCircuitPeeringsClient is the composite Swagger for Network +// Client type ExpressRouteCircuitPeeringsClient struct { ManagementClient } @@ -50,28 +47,41 @@ func NewExpressRouteCircuitPeeringsClientWithBaseURI(baseURI string, subscriptio // 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. +// 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 or update express // route circuit peering operation. -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", nil, "Failure preparing request") - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "CreateOrUpdate", resp, "Failure sending request") - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "CreateOrUpdate", resp, "Failure responding to request") - } - - return +func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdate(resourceGroupName string, circuitName string, peeringName string, peeringParameters ExpressRouteCircuitPeering, cancel <-chan struct{}) (<-chan ExpressRouteCircuitPeering, <-chan error) { + resultChan := make(chan ExpressRouteCircuitPeering, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result ExpressRouteCircuitPeering + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.CreateOrUpdatePreparer(resourceGroupName, circuitName, peeringName, peeringParameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "CreateOrUpdate", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. @@ -83,8 +93,9 @@ func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdatePreparer(resourceG "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -107,13 +118,14 @@ func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdateSender(req *http.R // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { +func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRouteCircuitPeering, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } @@ -122,26 +134,39 @@ func (client ExpressRouteCircuitPeeringsClient) CreateOrUpdateResponder(resp *ht // 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, 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", nil, "Failure preparing request") - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Delete", resp, "Failure sending request") - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Delete", resp, "Failure responding to request") - } - - return +// 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, cancel <-chan struct{}) (<-chan autorest.Response, <-chan error) { + resultChan := make(chan autorest.Response, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result autorest.Response + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeletePreparer(resourceGroupName, circuitName, peeringName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Delete", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // DeletePreparer prepares the Delete request. @@ -153,8 +178,9 @@ func (client ExpressRouteCircuitPeeringsClient) DeletePreparer(resourceGroupName "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -188,18 +214,20 @@ func (client ExpressRouteCircuitPeeringsClient) DeleteResponder(resp *http.Respo // Get gets the specified authorization from the specified express route // circuit. // -// resourceGroupName is the name of the resource group. circuitName is the -// name of the express route circuit. peeringName is the name of the peering. +// 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, err error) { req, err := client.GetPreparer(resourceGroupName, circuitName, peeringName) if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Get", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Get", nil, "Failure preparing request") + return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Get", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "Get", resp, "Failure sending request") + return } result, err = client.GetResponder(resp) @@ -219,8 +247,9 @@ func (client ExpressRouteCircuitPeeringsClient) GetPreparer(resourceGroupName st "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -252,18 +281,20 @@ func (client ExpressRouteCircuitPeeringsClient) GetResponder(resp *http.Response // List gets all peerings in a specified express route circuit. // -// resourceGroupName is the name of the resource group. circuitName is the -// name of the express route circuit. +// resourceGroupName is the name of the resource group. circuitName is the name +// of the express route circuit. 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", nil, "Failure preparing request") + return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitPeeringsClient", "List", resp, "Failure sending request") + return } result, err = client.ListResponder(resp) @@ -282,8 +313,9 @@ func (client ExpressRouteCircuitPeeringsClient) ListPreparer(resourceGroupName s "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( 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 old mode 100644 new mode 100755 index 6572e92b625f..b60aa10a4e94 --- 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,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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -24,11 +24,7 @@ import ( "net/http" ) -// ExpressRouteCircuitsClient 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 resources. The API has -// entities that capture the relationship between an end user and the -// Microsoft Azure Networks service. +// ExpressRouteCircuitsClient is the composite Swagger for Network Client type ExpressRouteCircuitsClient struct { ManagementClient } @@ -50,27 +46,40 @@ func NewExpressRouteCircuitsClientWithBaseURI(baseURI string, subscriptionID str // 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 or -// update express route circuit operation. -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", nil, "Failure preparing request") - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "CreateOrUpdate", resp, "Failure sending request") - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "CreateOrUpdate", resp, "Failure responding to request") - } - - return +// resourceGroupName is the name of the resource group. circuitName is the name +// of the circuit. parameters is parameters supplied to the create or update +// express route circuit operation. +func (client ExpressRouteCircuitsClient) CreateOrUpdate(resourceGroupName string, circuitName string, parameters ExpressRouteCircuit, cancel <-chan struct{}) (<-chan ExpressRouteCircuit, <-chan error) { + resultChan := make(chan ExpressRouteCircuit, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result ExpressRouteCircuit + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.CreateOrUpdatePreparer(resourceGroupName, circuitName, parameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "CreateOrUpdate", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. @@ -81,8 +90,9 @@ func (client ExpressRouteCircuitsClient) CreateOrUpdatePreparer(resourceGroupNam "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -105,41 +115,55 @@ func (client ExpressRouteCircuitsClient) CreateOrUpdateSender(req *http.Request) // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client ExpressRouteCircuitsClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { +func (client ExpressRouteCircuitsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRouteCircuit, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } -// Delete deletes the specified express route circuit. 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. +// Delete deletes the specified express route circuit. 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, 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", nil, "Failure preparing request") - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Delete", resp, "Failure sending request") - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Delete", resp, "Failure responding to request") - } - - return +// 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, cancel <-chan struct{}) (<-chan autorest.Response, <-chan error) { + resultChan := make(chan autorest.Response, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result autorest.Response + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeletePreparer(resourceGroupName, circuitName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Delete", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // DeletePreparer prepares the Delete request. @@ -150,8 +174,9 @@ func (client ExpressRouteCircuitsClient) DeletePreparer(resourceGroupName string "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -184,18 +209,20 @@ func (client ExpressRouteCircuitsClient) DeleteResponder(resp *http.Response) (r // Get gets information about the specified express route circuit. // -// resourceGroupName is the name of the resource group. circuitName is the -// name of express route circuit. +// resourceGroupName is the name of the resource group. circuitName is the name +// of express route circuit. 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Get", nil, "Failure preparing request") + return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Get", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "Get", resp, "Failure sending request") + return } result, err = client.GetResponder(resp) @@ -214,8 +241,9 @@ func (client ExpressRouteCircuitsClient) GetPreparer(resourceGroupName string, c "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -248,18 +276,20 @@ func (client ExpressRouteCircuitsClient) GetResponder(resp *http.Response) (resu // GetPeeringStats gets all stats from an express route circuit in a resource // group. // -// resourceGroupName is the name of the resource group. circuitName is the -// name of the express route circuit. peeringName is the name of the peering. +// 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 ExpressRouteCircuitsClient) GetPeeringStats(resourceGroupName string, circuitName string, peeringName string) (result ExpressRouteCircuitStats, err error) { req, err := client.GetPeeringStatsPreparer(resourceGroupName, circuitName, peeringName) if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "GetPeeringStats", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "GetPeeringStats", nil, "Failure preparing request") + return } resp, err := client.GetPeeringStatsSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "GetPeeringStats", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "GetPeeringStats", resp, "Failure sending request") + return } result, err = client.GetPeeringStatsResponder(resp) @@ -279,8 +309,9 @@ func (client ExpressRouteCircuitsClient) GetPeeringStatsPreparer(resourceGroupNa "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -313,18 +344,20 @@ func (client ExpressRouteCircuitsClient) GetPeeringStatsResponder(resp *http.Res // GetStats gets all the stats from an express route circuit in a resource // group. // -// resourceGroupName is the name of the resource group. circuitName is the -// name of the express route circuit. +// resourceGroupName is the name of the resource group. circuitName is the name +// of the express route circuit. func (client ExpressRouteCircuitsClient) GetStats(resourceGroupName string, circuitName string) (result ExpressRouteCircuitStats, err error) { req, err := client.GetStatsPreparer(resourceGroupName, circuitName) if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "GetStats", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "GetStats", nil, "Failure preparing request") + return } resp, err := client.GetStatsSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "GetStats", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "GetStats", resp, "Failure sending request") + return } result, err = client.GetStatsResponder(resp) @@ -343,8 +376,9 @@ func (client ExpressRouteCircuitsClient) GetStatsPreparer(resourceGroupName stri "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -380,13 +414,15 @@ func (client ExpressRouteCircuitsClient) GetStatsResponder(resp *http.Response) 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "List", nil, "Failure preparing request") + return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "List", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "List", resp, "Failure sending request") + return } result, err = client.ListResponder(resp) @@ -404,8 +440,9 @@ func (client ExpressRouteCircuitsClient) ListPreparer(resourceGroupName string) "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -463,13 +500,15 @@ func (client ExpressRouteCircuitsClient) ListNextResults(lastResults ExpressRout func (client ExpressRouteCircuitsClient) ListAll() (result ExpressRouteCircuitListResult, err error) { req, err := client.ListAllPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListAll", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListAll", nil, "Failure preparing request") + return } resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListAll", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListAll", resp, "Failure sending request") + return } result, err = client.ListAllResponder(resp) @@ -486,8 +525,9 @@ func (client ExpressRouteCircuitsClient) ListAllPreparer() (*http.Request, error "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -543,31 +583,44 @@ func (client ExpressRouteCircuitsClient) ListAllNextResults(lastResults ExpressR // ListArpTable gets the currently advertised ARP table associated with the // express route circuit in a 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. +// 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. +// resourceGroupName is the name of the resource group. circuitName is the name +// of the express route circuit. peeringName is the name of the peering. // devicePath is the path of the device. -func (client ExpressRouteCircuitsClient) ListArpTable(resourceGroupName string, circuitName string, peeringName string, devicePath string, cancel <-chan struct{}) (result autorest.Response, err error) { - req, err := client.ListArpTablePreparer(resourceGroupName, circuitName, peeringName, devicePath, cancel) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListArpTable", nil, "Failure preparing request") - } - - resp, err := client.ListArpTableSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListArpTable", resp, "Failure sending request") - } - - result, err = client.ListArpTableResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListArpTable", resp, "Failure responding to request") - } - - return +func (client ExpressRouteCircuitsClient) ListArpTable(resourceGroupName string, circuitName string, peeringName string, devicePath string, cancel <-chan struct{}) (<-chan ExpressRouteCircuitsArpTableListResult, <-chan error) { + resultChan := make(chan ExpressRouteCircuitsArpTableListResult, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result ExpressRouteCircuitsArpTableListResult + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.ListArpTablePreparer(resourceGroupName, circuitName, peeringName, devicePath, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListArpTable", nil, "Failure preparing request") + return + } + + resp, err := client.ListArpTableSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListArpTable", resp, "Failure sending request") + return + } + + result, err = client.ListArpTableResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListArpTable", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // ListArpTablePreparer prepares the ListArpTable request. @@ -580,8 +633,9 @@ func (client ExpressRouteCircuitsClient) ListArpTablePreparer(resourceGroupName "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -602,43 +656,57 @@ func (client ExpressRouteCircuitsClient) ListArpTableSender(req *http.Request) ( // ListArpTableResponder handles the response to the ListArpTable request. The method always // closes the http.Response Body. -func (client ExpressRouteCircuitsClient) ListArpTableResponder(resp *http.Response) (result autorest.Response, err error) { +func (client ExpressRouteCircuitsClient) ListArpTableResponder(resp *http.Response) (result ExpressRouteCircuitsArpTableListResult, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } // ListRoutesTable gets the currently advertised routes table associated with // the express route circuit in a 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. +// 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. +// resourceGroupName is the name of the resource group. circuitName is the name +// of the express route circuit. peeringName is the name of the peering. // devicePath is the path of the device. -func (client ExpressRouteCircuitsClient) ListRoutesTable(resourceGroupName string, circuitName string, peeringName string, devicePath string, cancel <-chan struct{}) (result autorest.Response, err error) { - req, err := client.ListRoutesTablePreparer(resourceGroupName, circuitName, peeringName, devicePath, cancel) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTable", nil, "Failure preparing request") - } - - resp, err := client.ListRoutesTableSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTable", resp, "Failure sending request") - } - - result, err = client.ListRoutesTableResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTable", resp, "Failure responding to request") - } - - return +func (client ExpressRouteCircuitsClient) ListRoutesTable(resourceGroupName string, circuitName string, peeringName string, devicePath string, cancel <-chan struct{}) (<-chan ExpressRouteCircuitsRoutesTableListResult, <-chan error) { + resultChan := make(chan ExpressRouteCircuitsRoutesTableListResult, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result ExpressRouteCircuitsRoutesTableListResult + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.ListRoutesTablePreparer(resourceGroupName, circuitName, peeringName, devicePath, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTable", nil, "Failure preparing request") + return + } + + resp, err := client.ListRoutesTableSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTable", resp, "Failure sending request") + return + } + + result, err = client.ListRoutesTableResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTable", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // ListRoutesTablePreparer prepares the ListRoutesTable request. @@ -651,8 +719,9 @@ func (client ExpressRouteCircuitsClient) ListRoutesTablePreparer(resourceGroupNa "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -673,13 +742,14 @@ func (client ExpressRouteCircuitsClient) ListRoutesTableSender(req *http.Request // ListRoutesTableResponder handles the response to the ListRoutesTable request. The method always // closes the http.Response Body. -func (client ExpressRouteCircuitsClient) ListRoutesTableResponder(resp *http.Response) (result autorest.Response, err error) { +func (client ExpressRouteCircuitsClient) ListRoutesTableResponder(resp *http.Response) (result ExpressRouteCircuitsRoutesTableListResult, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } @@ -689,27 +759,40 @@ func (client ExpressRouteCircuitsClient) ListRoutesTableResponder(resp *http.Res // 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. +// resourceGroupName is the name of the resource group. circuitName is the name +// of the express route circuit. peeringName is the name of the peering. // devicePath is the path of the device. -func (client ExpressRouteCircuitsClient) ListRoutesTableSummary(resourceGroupName string, circuitName string, peeringName string, devicePath string, cancel <-chan struct{}) (result autorest.Response, err error) { - req, err := client.ListRoutesTableSummaryPreparer(resourceGroupName, circuitName, peeringName, devicePath, cancel) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTableSummary", nil, "Failure preparing request") - } - - resp, err := client.ListRoutesTableSummarySender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTableSummary", resp, "Failure sending request") - } - - result, err = client.ListRoutesTableSummaryResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTableSummary", resp, "Failure responding to request") - } - - return +func (client ExpressRouteCircuitsClient) ListRoutesTableSummary(resourceGroupName string, circuitName string, peeringName string, devicePath string, cancel <-chan struct{}) (<-chan ExpressRouteCircuitsRoutesTableSummaryListResult, <-chan error) { + resultChan := make(chan ExpressRouteCircuitsRoutesTableSummaryListResult, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result ExpressRouteCircuitsRoutesTableSummaryListResult + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.ListRoutesTableSummaryPreparer(resourceGroupName, circuitName, peeringName, devicePath, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTableSummary", nil, "Failure preparing request") + return + } + + resp, err := client.ListRoutesTableSummarySender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTableSummary", resp, "Failure sending request") + return + } + + result, err = client.ListRoutesTableSummaryResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.ExpressRouteCircuitsClient", "ListRoutesTableSummary", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // ListRoutesTableSummaryPreparer prepares the ListRoutesTableSummary request. @@ -722,8 +805,9 @@ func (client ExpressRouteCircuitsClient) ListRoutesTableSummaryPreparer(resource "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -744,12 +828,13 @@ func (client ExpressRouteCircuitsClient) ListRoutesTableSummarySender(req *http. // ListRoutesTableSummaryResponder handles the response to the ListRoutesTableSummary request. The method always // closes the http.Response Body. -func (client ExpressRouteCircuitsClient) ListRoutesTableSummaryResponder(resp *http.Response) (result autorest.Response, err error) { +func (client ExpressRouteCircuitsClient) ListRoutesTableSummaryResponder(resp *http.Response) (result ExpressRouteCircuitsRoutesTableSummaryListResult, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} 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 old mode 100644 new mode 100755 index 9d0450ecf093..94db9a4f6147 --- 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,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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -24,11 +24,8 @@ import ( "net/http" ) -// ExpressRouteServiceProvidersClient 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 resources. The API -// has entities that capture the relationship between an end user and the -// Microsoft Azure Networks service. +// ExpressRouteServiceProvidersClient is the composite Swagger for Network +// Client type ExpressRouteServiceProvidersClient struct { ManagementClient } @@ -49,13 +46,15 @@ func NewExpressRouteServiceProvidersClientWithBaseURI(baseURI string, subscripti func (client ExpressRouteServiceProvidersClient) List() (result ExpressRouteServiceProviderListResult, err error) { req, err := client.ListPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "List", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "List", nil, "Failure preparing request") + return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "List", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "List", resp, "Failure sending request") + return } result, err = client.ListResponder(resp) @@ -72,8 +71,9 @@ func (client ExpressRouteServiceProvidersClient) ListPreparer() (*http.Request, "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( 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 old mode 100644 new mode 100755 index 9fbf7cddd4a5..8918c08b4b70 --- 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,22 +14,17 @@ 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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" "net/http" ) -// InterfacesClient 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 resources. The API has entities that -// capture the relationship between an end user and the Microsoft Azure -// Networks service. +// InterfacesClient is the composite Swagger for Network Client type InterfacesClient struct { ManagementClient } @@ -50,40 +45,40 @@ func NewInterfacesClientWithBaseURI(baseURI string, subscriptionID string) Inter // 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 or update network interface operation. -func (client InterfacesClient) CreateOrUpdate(resourceGroupName string, networkInterfaceName string, parameters Interface, cancel <-chan struct{}) (result autorest.Response, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.InterfacePropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.InterfacePropertiesFormat.NetworkSecurityGroup", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.InterfacePropertiesFormat.NetworkSecurityGroup.SecurityGroupPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.InterfacePropertiesFormat.NetworkSecurityGroup.SecurityGroupPropertiesFormat.NetworkInterfaces", Name: validation.ReadOnly, Rule: true, Chain: nil}, - {Target: "parameters.InterfacePropertiesFormat.NetworkSecurityGroup.SecurityGroupPropertiesFormat.Subnets", Name: validation.ReadOnly, Rule: true, Chain: nil}, - }}, - }}, - }}}}}); err != nil { - return result, validation.NewErrorWithValidationError(err, "network.InterfacesClient", "CreateOrUpdate") - } - - req, err := client.CreateOrUpdatePreparer(resourceGroupName, networkInterfaceName, parameters, cancel) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "CreateOrUpdate", nil, "Failure preparing request") - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "CreateOrUpdate", resp, "Failure sending request") - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "CreateOrUpdate", resp, "Failure responding to request") - } - - return +// resourceGroupName is the name of the resource group. networkInterfaceName is +// the name of the network interface. parameters is parameters supplied to the +// create or update network interface operation. +func (client InterfacesClient) CreateOrUpdate(resourceGroupName string, networkInterfaceName string, parameters Interface, cancel <-chan struct{}) (<-chan Interface, <-chan error) { + resultChan := make(chan Interface, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result Interface + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.CreateOrUpdatePreparer(resourceGroupName, networkInterfaceName, parameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "CreateOrUpdate", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. @@ -94,8 +89,9 @@ func (client InterfacesClient) CreateOrUpdatePreparer(resourceGroupName string, "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -118,41 +114,55 @@ func (client InterfacesClient) CreateOrUpdateSender(req *http.Request) (*http.Re // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client InterfacesClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { +func (client InterfacesClient) CreateOrUpdateResponder(resp *http.Response) (result Interface, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } // Delete deletes the specified network interface. 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. +// 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, 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", nil, "Failure preparing request") - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "Delete", resp, "Failure sending request") - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "Delete", resp, "Failure responding to request") - } - - return +// resourceGroupName is the name of the resource group. networkInterfaceName is +// the name of the network interface. +func (client InterfacesClient) Delete(resourceGroupName string, networkInterfaceName string, cancel <-chan struct{}) (<-chan autorest.Response, <-chan error) { + resultChan := make(chan autorest.Response, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result autorest.Response + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeletePreparer(resourceGroupName, networkInterfaceName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "Delete", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // DeletePreparer prepares the Delete request. @@ -163,8 +173,9 @@ func (client InterfacesClient) DeletePreparer(resourceGroupName string, networkI "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -197,19 +208,20 @@ func (client InterfacesClient) DeleteResponder(resp *http.Response) (result auto // Get gets information about the specified network interface. // -// resourceGroupName is the name of the resource group. networkInterfaceName -// is the name of the network interface. expand is expands referenced -// resources. +// resourceGroupName is the name of the resource group. networkInterfaceName is +// the name of the network interface. expand is expands referenced resources. 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "Get", nil, "Failure preparing request") + return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "Get", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "Get", resp, "Failure sending request") + return } result, err = client.GetResponder(resp) @@ -228,8 +240,9 @@ func (client InterfacesClient) GetPreparer(resourceGroupName string, networkInte "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } if len(expand) > 0 { queryParameters["$expand"] = autorest.Encode("query", expand) @@ -262,31 +275,44 @@ func (client InterfacesClient) GetResponder(resp *http.Response) (result Interfa return } -// GetEffectiveRouteTable gets all route tables applied to a network -// interface. 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. +// GetEffectiveRouteTable gets all route tables applied to a network interface. +// 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) GetEffectiveRouteTable(resourceGroupName string, networkInterfaceName string, cancel <-chan struct{}) (result autorest.Response, err error) { - req, err := client.GetEffectiveRouteTablePreparer(resourceGroupName, networkInterfaceName, cancel) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "GetEffectiveRouteTable", nil, "Failure preparing request") - } - - resp, err := client.GetEffectiveRouteTableSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "GetEffectiveRouteTable", resp, "Failure sending request") - } - - result, err = client.GetEffectiveRouteTableResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "GetEffectiveRouteTable", resp, "Failure responding to request") - } - - return +// resourceGroupName is the name of the resource group. networkInterfaceName is +// the name of the network interface. +func (client InterfacesClient) GetEffectiveRouteTable(resourceGroupName string, networkInterfaceName string, cancel <-chan struct{}) (<-chan EffectiveRouteListResult, <-chan error) { + resultChan := make(chan EffectiveRouteListResult, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result EffectiveRouteListResult + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.GetEffectiveRouteTablePreparer(resourceGroupName, networkInterfaceName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "GetEffectiveRouteTable", nil, "Failure preparing request") + return + } + + resp, err := client.GetEffectiveRouteTableSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "GetEffectiveRouteTable", resp, "Failure sending request") + return + } + + result, err = client.GetEffectiveRouteTableResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "GetEffectiveRouteTable", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // GetEffectiveRouteTablePreparer prepares the GetEffectiveRouteTable request. @@ -297,8 +323,9 @@ func (client InterfacesClient) GetEffectiveRouteTablePreparer(resourceGroupName "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -319,13 +346,14 @@ func (client InterfacesClient) GetEffectiveRouteTableSender(req *http.Request) ( // GetEffectiveRouteTableResponder handles the response to the GetEffectiveRouteTable request. The method always // closes the http.Response Body. -func (client InterfacesClient) GetEffectiveRouteTableResponder(resp *http.Response) (result autorest.Response, err error) { +func (client InterfacesClient) GetEffectiveRouteTableResponder(resp *http.Response) (result EffectiveRouteListResult, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } @@ -339,13 +367,15 @@ func (client InterfacesClient) GetEffectiveRouteTableResponder(resp *http.Respon 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "GetVirtualMachineScaleSetNetworkInterface", nil, "Failure preparing request") + return } resp, err := client.GetVirtualMachineScaleSetNetworkInterfaceSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "GetVirtualMachineScaleSetNetworkInterface", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "GetVirtualMachineScaleSetNetworkInterface", resp, "Failure sending request") + return } result, err = client.GetVirtualMachineScaleSetNetworkInterfaceResponder(resp) @@ -366,8 +396,9 @@ func (client InterfacesClient) GetVirtualMachineScaleSetNetworkInterfacePreparer "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), } + const APIVersion = "2016-09-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } if len(expand) > 0 { queryParameters["$expand"] = autorest.Encode("query", expand) @@ -406,13 +437,15 @@ func (client InterfacesClient) GetVirtualMachineScaleSetNetworkInterfaceResponde 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "List", nil, "Failure preparing request") + return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "List", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "List", resp, "Failure sending request") + return } result, err = client.ListResponder(resp) @@ -430,8 +463,9 @@ func (client InterfacesClient) ListPreparer(resourceGroupName string) (*http.Req "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -489,13 +523,15 @@ func (client InterfacesClient) ListNextResults(lastResults InterfaceListResult) func (client InterfacesClient) ListAll() (result InterfaceListResult, err error) { req, err := client.ListAllPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "ListAll", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListAll", nil, "Failure preparing request") + return } resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "ListAll", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListAll", resp, "Failure sending request") + return } result, err = client.ListAllResponder(resp) @@ -512,8 +548,9 @@ func (client InterfacesClient) ListAllPreparer() (*http.Request, error) { "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -568,30 +605,43 @@ func (client InterfacesClient) ListAllNextResults(lastResults InterfaceListResul } // ListEffectiveNetworkSecurityGroups gets all network security groups applied -// to a network interface. 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. +// to a network interface. 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) ListEffectiveNetworkSecurityGroups(resourceGroupName string, networkInterfaceName string, cancel <-chan struct{}) (result autorest.Response, err error) { - req, err := client.ListEffectiveNetworkSecurityGroupsPreparer(resourceGroupName, networkInterfaceName, cancel) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "ListEffectiveNetworkSecurityGroups", nil, "Failure preparing request") - } - - resp, err := client.ListEffectiveNetworkSecurityGroupsSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "ListEffectiveNetworkSecurityGroups", resp, "Failure sending request") - } - - result, err = client.ListEffectiveNetworkSecurityGroupsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListEffectiveNetworkSecurityGroups", resp, "Failure responding to request") - } - - return +// resourceGroupName is the name of the resource group. networkInterfaceName is +// the name of the network interface. +func (client InterfacesClient) ListEffectiveNetworkSecurityGroups(resourceGroupName string, networkInterfaceName string, cancel <-chan struct{}) (<-chan EffectiveNetworkSecurityGroupListResult, <-chan error) { + resultChan := make(chan EffectiveNetworkSecurityGroupListResult, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result EffectiveNetworkSecurityGroupListResult + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.ListEffectiveNetworkSecurityGroupsPreparer(resourceGroupName, networkInterfaceName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListEffectiveNetworkSecurityGroups", nil, "Failure preparing request") + return + } + + resp, err := client.ListEffectiveNetworkSecurityGroupsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListEffectiveNetworkSecurityGroups", resp, "Failure sending request") + return + } + + result, err = client.ListEffectiveNetworkSecurityGroupsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListEffectiveNetworkSecurityGroups", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // ListEffectiveNetworkSecurityGroupsPreparer prepares the ListEffectiveNetworkSecurityGroups request. @@ -602,8 +652,9 @@ func (client InterfacesClient) ListEffectiveNetworkSecurityGroupsPreparer(resour "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -624,31 +675,34 @@ func (client InterfacesClient) ListEffectiveNetworkSecurityGroupsSender(req *htt // ListEffectiveNetworkSecurityGroupsResponder handles the response to the ListEffectiveNetworkSecurityGroups request. The method always // closes the http.Response Body. -func (client InterfacesClient) ListEffectiveNetworkSecurityGroupsResponder(resp *http.Response) (result autorest.Response, err error) { +func (client InterfacesClient) ListEffectiveNetworkSecurityGroupsResponder(resp *http.Response) (result EffectiveNetworkSecurityGroupListResult, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } -// ListVirtualMachineScaleSetNetworkInterfaces gets all network interfaces in -// a virtual machine scale set. +// ListVirtualMachineScaleSetNetworkInterfaces gets all network interfaces in a +// virtual machine scale set. // // 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, err error) { req, err := client.ListVirtualMachineScaleSetNetworkInterfacesPreparer(resourceGroupName, virtualMachineScaleSetName) if err != nil { - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetNetworkInterfaces", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetNetworkInterfaces", nil, "Failure preparing request") + return } resp, err := client.ListVirtualMachineScaleSetNetworkInterfacesSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetNetworkInterfaces", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetNetworkInterfaces", resp, "Failure sending request") + return } result, err = client.ListVirtualMachineScaleSetNetworkInterfacesResponder(resp) @@ -667,8 +721,9 @@ func (client InterfacesClient) ListVirtualMachineScaleSetNetworkInterfacesPrepar "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), } + const APIVersion = "2016-09-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -731,13 +786,15 @@ func (client InterfacesClient) ListVirtualMachineScaleSetNetworkInterfacesNextRe 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetVMNetworkInterfaces", nil, "Failure preparing request") + return } resp, err := client.ListVirtualMachineScaleSetVMNetworkInterfacesSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetVMNetworkInterfaces", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.InterfacesClient", "ListVirtualMachineScaleSetVMNetworkInterfaces", resp, "Failure sending request") + return } result, err = client.ListVirtualMachineScaleSetVMNetworkInterfacesResponder(resp) @@ -757,8 +814,9 @@ func (client InterfacesClient) ListVirtualMachineScaleSetVMNetworkInterfacesPrep "virtualMachineScaleSetName": autorest.Encode("path", virtualMachineScaleSetName), } + const APIVersion = "2016-09-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( 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 old mode 100644 new mode 100755 index 30012ff35b90..11d649b270a0 --- 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,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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -24,11 +24,7 @@ import ( "net/http" ) -// LoadBalancersClient 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 resources. The API has entities -// that capture the relationship between an end user and the Microsoft Azure -// Networks service. +// LoadBalancersClient is the composite Swagger for Network Client type LoadBalancersClient struct { ManagementClient } @@ -46,31 +42,44 @@ func NewLoadBalancersClientWithBaseURI(baseURI string, subscriptionID string) Lo } // CreateOrUpdate creates or updates a load balancer. 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. +// 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 load balancer. parameters is parameters supplied to the -// create or update load balancer operation. -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", nil, "Failure preparing request") - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "CreateOrUpdate", resp, "Failure sending request") - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "CreateOrUpdate", resp, "Failure responding to request") - } - - return +// resourceGroupName is the name of the resource group. loadBalancerName is the +// name of the load balancer. parameters is parameters supplied to the create +// or update load balancer operation. +func (client LoadBalancersClient) CreateOrUpdate(resourceGroupName string, loadBalancerName string, parameters LoadBalancer, cancel <-chan struct{}) (<-chan LoadBalancer, <-chan error) { + resultChan := make(chan LoadBalancer, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result LoadBalancer + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.CreateOrUpdatePreparer(resourceGroupName, loadBalancerName, parameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "CreateOrUpdate", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. @@ -81,8 +90,9 @@ func (client LoadBalancersClient) CreateOrUpdatePreparer(resourceGroupName strin "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -105,41 +115,55 @@ func (client LoadBalancersClient) CreateOrUpdateSender(req *http.Request) (*http // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client LoadBalancersClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { +func (client LoadBalancersClient) CreateOrUpdateResponder(resp *http.Response) (result LoadBalancer, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } // Delete deletes the specified load balancer. 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. +// 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 load balancer. -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", nil, "Failure preparing request") - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Delete", resp, "Failure sending request") - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Delete", resp, "Failure responding to request") - } - - return +// resourceGroupName is the name of the resource group. loadBalancerName is the +// name of the load balancer. +func (client LoadBalancersClient) Delete(resourceGroupName string, loadBalancerName string, cancel <-chan struct{}) (<-chan autorest.Response, <-chan error) { + resultChan := make(chan autorest.Response, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result autorest.Response + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeletePreparer(resourceGroupName, loadBalancerName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Delete", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // DeletePreparer prepares the Delete request. @@ -150,8 +174,9 @@ func (client LoadBalancersClient) DeletePreparer(resourceGroupName string, loadB "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -184,18 +209,20 @@ func (client LoadBalancersClient) DeleteResponder(resp *http.Response) (result a // Get gets the specified load balancer. // -// resourceGroupName is the name of the resource group. loadBalancerName is -// the name of the load balancer. expand is expands referenced resources. +// resourceGroupName is the name of the resource group. loadBalancerName is the +// name of the load balancer. expand is expands referenced resources. 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Get", nil, "Failure preparing request") + return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Get", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Get", resp, "Failure sending request") + return } result, err = client.GetResponder(resp) @@ -214,8 +241,9 @@ func (client LoadBalancersClient) GetPreparer(resourceGroupName string, loadBala "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } if len(expand) > 0 { queryParameters["$expand"] = autorest.Encode("query", expand) @@ -254,13 +282,15 @@ func (client LoadBalancersClient) GetResponder(resp *http.Response) (result Load 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "List", nil, "Failure preparing request") + return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "List", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "List", resp, "Failure sending request") + return } result, err = client.ListResponder(resp) @@ -278,8 +308,9 @@ func (client LoadBalancersClient) ListPreparer(resourceGroupName string) (*http. "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -337,13 +368,15 @@ func (client LoadBalancersClient) ListNextResults(lastResults LoadBalancerListRe func (client LoadBalancersClient) ListAll() (result LoadBalancerListResult, err error) { req, err := client.ListAllPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListAll", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListAll", nil, "Failure preparing request") + return } resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListAll", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListAll", resp, "Failure sending request") + return } result, err = client.ListAllResponder(resp) @@ -360,8 +393,9 @@ func (client LoadBalancersClient) ListAllPreparer() (*http.Request, error) { "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( 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 old mode 100644 new mode 100755 index fd48306f245d..c1e66076e198 --- 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,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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -25,11 +25,7 @@ import ( "net/http" ) -// LocalNetworkGatewaysClient 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 resources. The API has -// entities that capture the relationship between an end user and the -// Microsoft Azure Networks service. +// LocalNetworkGatewaysClient is the composite Swagger for Network Client type LocalNetworkGatewaysClient struct { ManagementClient } @@ -47,41 +43,55 @@ func NewLocalNetworkGatewaysClientWithBaseURI(baseURI string, subscriptionID str } // CreateOrUpdate creates or updates a local network gateway 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. +// 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. -// localNetworkGatewayName is the name of the local network gateway. -// parameters is parameters supplied to the create or update local network -// gateway operation. -func (client LocalNetworkGatewaysClient) CreateOrUpdate(resourceGroupName string, localNetworkGatewayName string, parameters LocalNetworkGateway, cancel <-chan struct{}) (result autorest.Response, err error) { +// resourceGroupName is the name of the resource group. localNetworkGatewayName +// is the name of the local network gateway. parameters is parameters supplied +// to the create or update local network gateway operation. +func (client LocalNetworkGatewaysClient) CreateOrUpdate(resourceGroupName string, localNetworkGatewayName string, parameters LocalNetworkGateway, cancel <-chan struct{}) (<-chan LocalNetworkGateway, <-chan error) { + resultChan := make(chan LocalNetworkGateway, 1) + errChan := make(chan error, 1) if err := validation.Validate([]validation.Validation{ + {TargetValue: localNetworkGatewayName, + Constraints: []validation.Constraint{{Target: "localNetworkGatewayName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.LocalNetworkGatewayPropertiesFormat", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "parameters.LocalNetworkGatewayPropertiesFormat.LocalNetworkAddressSpace", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.LocalNetworkGatewayPropertiesFormat.ProvisioningState", Name: validation.ReadOnly, Rule: true, Chain: nil}, - }}}}}); err != nil { - return result, validation.NewErrorWithValidationError(err, "network.LocalNetworkGatewaysClient", "CreateOrUpdate") - } - - req, err := client.CreateOrUpdatePreparer(resourceGroupName, localNetworkGatewayName, parameters, cancel) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "CreateOrUpdate", nil, "Failure preparing request") - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "CreateOrUpdate", resp, "Failure sending request") - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "CreateOrUpdate", resp, "Failure responding to request") + Constraints: []validation.Constraint{{Target: "parameters.LocalNetworkGatewayPropertiesFormat", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + errChan <- validation.NewErrorWithValidationError(err, "network.LocalNetworkGatewaysClient", "CreateOrUpdate") + close(errChan) + close(resultChan) + return resultChan, errChan } - return + go func() { + var err error + var result LocalNetworkGateway + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.CreateOrUpdatePreparer(resourceGroupName, localNetworkGatewayName, parameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "CreateOrUpdate", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. @@ -92,8 +102,9 @@ func (client LocalNetworkGatewaysClient) CreateOrUpdatePreparer(resourceGroupNam "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -116,41 +127,64 @@ func (client LocalNetworkGatewaysClient) CreateOrUpdateSender(req *http.Request) // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client LocalNetworkGatewaysClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { +func (client LocalNetworkGatewaysClient) CreateOrUpdateResponder(resp *http.Response) (result LocalNetworkGateway, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } -// Delete deletes the specified local network gateway. 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. +// Delete deletes the specified local network gateway. 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, 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", nil, "Failure preparing request") - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "Delete", resp, "Failure sending request") - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "Delete", resp, "Failure responding to request") +// 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, cancel <-chan struct{}) (<-chan autorest.Response, <-chan error) { + resultChan := make(chan autorest.Response, 1) + errChan := make(chan error, 1) + if err := validation.Validate([]validation.Validation{ + {TargetValue: localNetworkGatewayName, + Constraints: []validation.Constraint{{Target: "localNetworkGatewayName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + errChan <- validation.NewErrorWithValidationError(err, "network.LocalNetworkGatewaysClient", "Delete") + close(errChan) + close(resultChan) + return resultChan, errChan } - return + go func() { + var err error + var result autorest.Response + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeletePreparer(resourceGroupName, localNetworkGatewayName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "Delete", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // DeletePreparer prepares the Delete request. @@ -161,8 +195,9 @@ func (client LocalNetworkGatewaysClient) DeletePreparer(resourceGroupName string "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -195,18 +230,26 @@ func (client LocalNetworkGatewaysClient) DeleteResponder(resp *http.Response) (r // Get gets the specified local network gateway in a resource group. // -// resourceGroupName is the name of the resource group. -// localNetworkGatewayName is the name of the local network gateway. +// 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, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: localNetworkGatewayName, + Constraints: []validation.Constraint{{Target: "localNetworkGatewayName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewErrorWithValidationError(err, "network.LocalNetworkGatewaysClient", "Get") + } + req, err := client.GetPreparer(resourceGroupName, localNetworkGatewayName) if err != nil { - return result, autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "Get", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "Get", nil, "Failure preparing request") + return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "Get", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "Get", resp, "Failure sending request") + return } result, err = client.GetResponder(resp) @@ -225,8 +268,9 @@ func (client LocalNetworkGatewaysClient) GetPreparer(resourceGroupName string, l "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -262,13 +306,15 @@ func (client LocalNetworkGatewaysClient) GetResponder(resp *http.Response) (resu 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "List", nil, "Failure preparing request") + return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "List", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.LocalNetworkGatewaysClient", "List", resp, "Failure sending request") + return } result, err = client.ListResponder(resp) @@ -286,8 +332,9 @@ func (client LocalNetworkGatewaysClient) ListPreparer(resourceGroupName string) "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( 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 old mode 100644 new mode 100755 index bb514f796b31..505691db01b3 --- 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,16 +14,27 @@ 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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/date" "github.com/Azure/go-autorest/autorest/to" "net/http" ) +// Access enumerates the values for access. +type Access string + +const ( + // Allow specifies the allow state for access. + Allow Access = "Allow" + // Deny specifies the deny state for access. + Deny Access = "Deny" +) + // ApplicationGatewayBackendHealthServerHealth enumerates the values for // application gateway backend health server health. type ApplicationGatewayBackendHealthServerHealth string @@ -32,6 +43,9 @@ const ( // Down specifies the down state for application gateway backend health // server health. Down ApplicationGatewayBackendHealthServerHealth = "Down" + // Draining specifies the draining state for application gateway backend + // health server health. + Draining ApplicationGatewayBackendHealthServerHealth = "Draining" // Partial specifies the partial state for application gateway backend // health server health. Partial ApplicationGatewayBackendHealthServerHealth = "Partial" @@ -51,18 +65,18 @@ const ( // Disabled specifies the disabled state for application gateway cookie // based affinity. Disabled ApplicationGatewayCookieBasedAffinity = "Disabled" - // Enabled specifies the enabled state for application gateway cookie - // based affinity. + // Enabled specifies the enabled state for application gateway cookie based + // affinity. Enabled ApplicationGatewayCookieBasedAffinity = "Enabled" ) -// ApplicationGatewayFirewallMode enumerates the values for application -// gateway firewall mode. +// ApplicationGatewayFirewallMode enumerates the values for application gateway +// firewall mode. type ApplicationGatewayFirewallMode string const ( - // Detection specifies the detection state for application gateway - // firewall mode. + // Detection specifies the detection state for application gateway firewall + // mode. Detection ApplicationGatewayFirewallMode = "Detection" // Prevention specifies the prevention state for application gateway // firewall mode. @@ -117,14 +131,14 @@ const ( type ApplicationGatewaySkuName string const ( - // StandardLarge specifies the standard large state for application - // gateway sku name. + // StandardLarge specifies the standard large state for application gateway + // sku name. StandardLarge ApplicationGatewaySkuName = "Standard_Large" // StandardMedium specifies the standard medium state for application // gateway sku name. StandardMedium ApplicationGatewaySkuName = "Standard_Medium" - // StandardSmall specifies the standard small state for application - // gateway sku name. + // StandardSmall specifies the standard small state for application gateway + // sku name. StandardSmall ApplicationGatewaySkuName = "Standard_Small" // WAFLarge specifies the waf large state for application gateway sku name. WAFLarge ApplicationGatewaySkuName = "WAF_Large" @@ -159,6 +173,16 @@ const ( WAF ApplicationGatewayTier = "WAF" ) +// AssociationType enumerates the values for association type. +type AssociationType string + +const ( + // Associated specifies the associated state for association type. + Associated AssociationType = "Associated" + // Contains specifies the contains state for association type. + Contains AssociationType = "Contains" +) + // AuthorizationUseStatus enumerates the values for authorization use status. type AuthorizationUseStatus string @@ -169,18 +193,71 @@ const ( InUse AuthorizationUseStatus = "InUse" ) +// BgpPeerState enumerates the values for bgp peer state. +type BgpPeerState string + +const ( + // BgpPeerStateConnected specifies the bgp peer state connected state for + // bgp peer state. + BgpPeerStateConnected BgpPeerState = "Connected" + // BgpPeerStateConnecting specifies the bgp peer state connecting state for + // bgp peer state. + BgpPeerStateConnecting BgpPeerState = "Connecting" + // BgpPeerStateIdle specifies the bgp peer state idle state for bgp peer + // state. + BgpPeerStateIdle BgpPeerState = "Idle" + // BgpPeerStateStopped specifies the bgp peer state stopped state for bgp + // peer state. + BgpPeerStateStopped BgpPeerState = "Stopped" + // BgpPeerStateUnknown specifies the bgp peer state unknown state for bgp + // peer state. + BgpPeerStateUnknown BgpPeerState = "Unknown" +) + +// DhGroup enumerates the values for dh group. +type DhGroup string + +const ( + // DHGroup1 specifies the dh group 1 state for dh group. + DHGroup1 DhGroup = "DHGroup1" + // DHGroup14 specifies the dh group 14 state for dh group. + DHGroup14 DhGroup = "DHGroup14" + // DHGroup2 specifies the dh group 2 state for dh group. + DHGroup2 DhGroup = "DHGroup2" + // DHGroup2048 specifies the dh group 2048 state for dh group. + DHGroup2048 DhGroup = "DHGroup2048" + // DHGroup24 specifies the dh group 24 state for dh group. + DHGroup24 DhGroup = "DHGroup24" + // ECP256 specifies the ecp256 state for dh group. + ECP256 DhGroup = "ECP256" + // ECP384 specifies the ecp384 state for dh group. + ECP384 DhGroup = "ECP384" + // None specifies the none state for dh group. + None DhGroup = "None" +) + +// Direction enumerates the values for direction. +type Direction string + +const ( + // Inbound specifies the inbound state for direction. + Inbound Direction = "Inbound" + // Outbound specifies the outbound state for direction. + Outbound Direction = "Outbound" +) + // EffectiveRouteSource enumerates the values for effective route source. type EffectiveRouteSource string const ( - // EffectiveRouteSourceDefault specifies the effective route source - // default state for effective route source. + // EffectiveRouteSourceDefault specifies the effective route source default + // state for effective route source. EffectiveRouteSourceDefault EffectiveRouteSource = "Default" - // EffectiveRouteSourceUnknown specifies the effective route source - // unknown state for effective route source. - EffectiveRouteSourceUnknown EffectiveRouteSource = "Unknown" - // EffectiveRouteSourceUser specifies the effective route source user + // EffectiveRouteSourceUnknown specifies the effective route source unknown // state for effective route source. + EffectiveRouteSourceUnknown EffectiveRouteSource = "Unknown" + // EffectiveRouteSourceUser specifies the effective route source user state + // for effective route source. EffectiveRouteSourceUser EffectiveRouteSource = "User" // EffectiveRouteSourceVirtualNetworkGateway specifies the effective route // source virtual network gateway state for effective route source. @@ -211,8 +288,8 @@ const ( // NotConfigured specifies the not configured state for express route // circuit peering advertised public prefix state. NotConfigured ExpressRouteCircuitPeeringAdvertisedPublicPrefixState = "NotConfigured" - // ValidationNeeded specifies the validation needed state for express - // route circuit peering advertised public prefix state. + // ValidationNeeded specifies the validation needed state for express route + // circuit peering advertised public prefix state. ValidationNeeded ExpressRouteCircuitPeeringAdvertisedPublicPrefixState = "ValidationNeeded" ) @@ -242,13 +319,13 @@ const ( // AzurePublicPeering specifies the azure public peering state for express // route circuit peering type. AzurePublicPeering ExpressRouteCircuitPeeringType = "AzurePublicPeering" - // MicrosoftPeering specifies the microsoft peering state for express - // route circuit peering type. + // MicrosoftPeering specifies the microsoft peering state for express route + // circuit peering type. MicrosoftPeering ExpressRouteCircuitPeeringType = "MicrosoftPeering" ) -// ExpressRouteCircuitSkuFamily enumerates the values for express route -// circuit sku family. +// ExpressRouteCircuitSkuFamily enumerates the values for express route circuit +// sku family. type ExpressRouteCircuitSkuFamily string const ( @@ -273,6 +350,36 @@ const ( ExpressRouteCircuitSkuTierStandard ExpressRouteCircuitSkuTier = "Standard" ) +// IkeEncryption enumerates the values for ike encryption. +type IkeEncryption string + +const ( + // AES128 specifies the aes128 state for ike encryption. + AES128 IkeEncryption = "AES128" + // AES192 specifies the aes192 state for ike encryption. + AES192 IkeEncryption = "AES192" + // AES256 specifies the aes256 state for ike encryption. + AES256 IkeEncryption = "AES256" + // DES specifies the des state for ike encryption. + DES IkeEncryption = "DES" + // DES3 specifies the des3 state for ike encryption. + DES3 IkeEncryption = "DES3" +) + +// IkeIntegrity enumerates the values for ike integrity. +type IkeIntegrity string + +const ( + // MD5 specifies the md5 state for ike integrity. + MD5 IkeIntegrity = "MD5" + // SHA1 specifies the sha1 state for ike integrity. + SHA1 IkeIntegrity = "SHA1" + // SHA256 specifies the sha256 state for ike integrity. + SHA256 IkeIntegrity = "SHA256" + // SHA384 specifies the sha384 state for ike integrity. + SHA384 IkeIntegrity = "SHA384" +) + // IPAllocationMethod enumerates the values for ip allocation method. type IPAllocationMethod string @@ -283,6 +390,63 @@ const ( Static IPAllocationMethod = "Static" ) +// IpsecEncryption enumerates the values for ipsec encryption. +type IpsecEncryption string + +const ( + // IpsecEncryptionAES128 specifies the ipsec encryption aes128 state for + // ipsec encryption. + IpsecEncryptionAES128 IpsecEncryption = "AES128" + // IpsecEncryptionAES192 specifies the ipsec encryption aes192 state for + // ipsec encryption. + IpsecEncryptionAES192 IpsecEncryption = "AES192" + // IpsecEncryptionAES256 specifies the ipsec encryption aes256 state for + // ipsec encryption. + IpsecEncryptionAES256 IpsecEncryption = "AES256" + // IpsecEncryptionDES specifies the ipsec encryption des state for ipsec + // encryption. + IpsecEncryptionDES IpsecEncryption = "DES" + // IpsecEncryptionDES3 specifies the ipsec encryption des3 state for ipsec + // encryption. + IpsecEncryptionDES3 IpsecEncryption = "DES3" + // IpsecEncryptionGCMAES128 specifies the ipsec encryption gcmaes128 state + // for ipsec encryption. + IpsecEncryptionGCMAES128 IpsecEncryption = "GCMAES128" + // IpsecEncryptionGCMAES192 specifies the ipsec encryption gcmaes192 state + // for ipsec encryption. + IpsecEncryptionGCMAES192 IpsecEncryption = "GCMAES192" + // IpsecEncryptionGCMAES256 specifies the ipsec encryption gcmaes256 state + // for ipsec encryption. + IpsecEncryptionGCMAES256 IpsecEncryption = "GCMAES256" + // IpsecEncryptionNone specifies the ipsec encryption none state for ipsec + // encryption. + IpsecEncryptionNone IpsecEncryption = "None" +) + +// IpsecIntegrity enumerates the values for ipsec integrity. +type IpsecIntegrity string + +const ( + // IpsecIntegrityGCMAES128 specifies the ipsec integrity gcmaes128 state + // for ipsec integrity. + IpsecIntegrityGCMAES128 IpsecIntegrity = "GCMAES128" + // IpsecIntegrityGCMAES192 specifies the ipsec integrity gcmaes192 state + // for ipsec integrity. + IpsecIntegrityGCMAES192 IpsecIntegrity = "GCMAES192" + // IpsecIntegrityGCMAES256 specifies the ipsec integrity gcmaes256 state + // for ipsec integrity. + IpsecIntegrityGCMAES256 IpsecIntegrity = "GCMAES256" + // IpsecIntegrityMD5 specifies the ipsec integrity md5 state for ipsec + // integrity. + IpsecIntegrityMD5 IpsecIntegrity = "MD5" + // IpsecIntegritySHA1 specifies the ipsec integrity sha1 state for ipsec + // integrity. + IpsecIntegritySHA1 IpsecIntegrity = "SHA1" + // IpsecIntegritySHA256 specifies the ipsec integrity sha256 state for + // ipsec integrity. + IpsecIntegritySHA256 IpsecIntegrity = "SHA256" +) + // IPVersion enumerates the values for ip version. type IPVersion string @@ -306,6 +470,30 @@ const ( SourceIPProtocol LoadDistribution = "SourceIPProtocol" ) +// NextHopType enumerates the values for next hop type. +type NextHopType string + +const ( + // NextHopTypeHyperNetGateway specifies the next hop type hyper net gateway + // state for next hop type. + NextHopTypeHyperNetGateway NextHopType = "HyperNetGateway" + // NextHopTypeInternet specifies the next hop type internet state for next + // hop type. + NextHopTypeInternet NextHopType = "Internet" + // NextHopTypeNone specifies the next hop type none state for next hop + // type. + NextHopTypeNone NextHopType = "None" + // NextHopTypeVirtualAppliance specifies the next hop type virtual + // appliance state for next hop type. + NextHopTypeVirtualAppliance NextHopType = "VirtualAppliance" + // NextHopTypeVirtualNetworkGateway specifies the next hop type virtual + // network gateway state for next hop type. + NextHopTypeVirtualNetworkGateway NextHopType = "VirtualNetworkGateway" + // NextHopTypeVnetLocal specifies the next hop type vnet local state for + // next hop type. + NextHopTypeVnetLocal NextHopType = "VnetLocal" +) + // OperationStatus enumerates the values for operation status. type OperationStatus string @@ -318,6 +506,71 @@ const ( Succeeded OperationStatus = "Succeeded" ) +// PcError enumerates the values for pc error. +type PcError string + +const ( + // AgentStopped specifies the agent stopped state for pc error. + AgentStopped PcError = "AgentStopped" + // CaptureFailed specifies the capture failed state for pc error. + CaptureFailed PcError = "CaptureFailed" + // InternalError specifies the internal error state for pc error. + InternalError PcError = "InternalError" + // LocalFileFailed specifies the local file failed state for pc error. + LocalFileFailed PcError = "LocalFileFailed" + // StorageFailed specifies the storage failed state for pc error. + StorageFailed PcError = "StorageFailed" +) + +// PcProtocol enumerates the values for pc protocol. +type PcProtocol string + +const ( + // Any specifies the any state for pc protocol. + Any PcProtocol = "Any" + // TCP specifies the tcp state for pc protocol. + TCP PcProtocol = "TCP" + // UDP specifies the udp state for pc protocol. + UDP PcProtocol = "UDP" +) + +// PcStatus enumerates the values for pc status. +type PcStatus string + +const ( + // PcStatusError specifies the pc status error state for pc status. + PcStatusError PcStatus = "Error" + // PcStatusNotStarted specifies the pc status not started state for pc + // status. + PcStatusNotStarted PcStatus = "NotStarted" + // PcStatusRunning specifies the pc status running state for pc status. + PcStatusRunning PcStatus = "Running" + // PcStatusStopped specifies the pc status stopped state for pc status. + PcStatusStopped PcStatus = "Stopped" + // PcStatusUnknown specifies the pc status unknown state for pc status. + PcStatusUnknown PcStatus = "Unknown" +) + +// PfsGroup enumerates the values for pfs group. +type PfsGroup string + +const ( + // PfsGroupECP256 specifies the pfs group ecp256 state for pfs group. + PfsGroupECP256 PfsGroup = "ECP256" + // PfsGroupECP384 specifies the pfs group ecp384 state for pfs group. + PfsGroupECP384 PfsGroup = "ECP384" + // PfsGroupNone specifies the pfs group none state for pfs group. + PfsGroupNone PfsGroup = "None" + // PfsGroupPFS1 specifies the pfs group pfs1 state for pfs group. + PfsGroupPFS1 PfsGroup = "PFS1" + // PfsGroupPFS2 specifies the pfs group pfs2 state for pfs group. + PfsGroupPFS2 PfsGroup = "PFS2" + // PfsGroupPFS2048 specifies the pfs group pfs2048 state for pfs group. + PfsGroupPFS2048 PfsGroup = "PFS2048" + // PfsGroupPFS24 specifies the pfs group pfs24 state for pfs group. + PfsGroupPFS24 PfsGroup = "PFS24" +) + // ProbeProtocol enumerates the values for probe protocol. type ProbeProtocol string @@ -340,6 +593,34 @@ const ( X86 ProcessorArchitecture = "X86" ) +// Protocol enumerates the values for protocol. +type Protocol string + +const ( + // ProtocolTCP specifies the protocol tcp state for protocol. + ProtocolTCP Protocol = "TCP" + // ProtocolUDP specifies the protocol udp state for protocol. + ProtocolUDP Protocol = "UDP" +) + +// ProvisioningState enumerates the values for provisioning state. +type ProvisioningState string + +const ( + // ProvisioningStateDeleting specifies the provisioning state deleting + // state for provisioning state. + ProvisioningStateDeleting ProvisioningState = "Deleting" + // ProvisioningStateFailed specifies the provisioning state failed state + // for provisioning state. + ProvisioningStateFailed ProvisioningState = "Failed" + // ProvisioningStateSucceeded specifies the provisioning state succeeded + // state for provisioning state. + ProvisioningStateSucceeded ProvisioningState = "Succeeded" + // ProvisioningStateUpdating specifies the provisioning state updating + // state for provisioning state. + ProvisioningStateUpdating ProvisioningState = "Updating" +) + // RouteNextHopType enumerates the values for route next hop type. type RouteNextHopType string @@ -365,32 +646,39 @@ const ( type SecurityRuleAccess string const ( - // Allow specifies the allow state for security rule access. - Allow SecurityRuleAccess = "Allow" - // Deny specifies the deny state for security rule access. - Deny SecurityRuleAccess = "Deny" + // SecurityRuleAccessAllow specifies the security rule access allow state + // for security rule access. + SecurityRuleAccessAllow SecurityRuleAccess = "Allow" + // SecurityRuleAccessDeny specifies the security rule access deny state for + // security rule access. + SecurityRuleAccessDeny SecurityRuleAccess = "Deny" ) // SecurityRuleDirection enumerates the values for security rule direction. type SecurityRuleDirection string const ( - // Inbound specifies the inbound state for security rule direction. - Inbound SecurityRuleDirection = "Inbound" - // Outbound specifies the outbound state for security rule direction. - Outbound SecurityRuleDirection = "Outbound" + // SecurityRuleDirectionInbound specifies the security rule direction + // inbound state for security rule direction. + SecurityRuleDirectionInbound SecurityRuleDirection = "Inbound" + // SecurityRuleDirectionOutbound specifies the security rule direction + // outbound state for security rule direction. + SecurityRuleDirectionOutbound SecurityRuleDirection = "Outbound" ) // SecurityRuleProtocol enumerates the values for security rule protocol. type SecurityRuleProtocol string const ( - // Asterisk specifies the asterisk state for security rule protocol. - Asterisk SecurityRuleProtocol = "*" - // TCP specifies the tcp state for security rule protocol. - TCP SecurityRuleProtocol = "Tcp" - // UDP specifies the udp state for security rule protocol. - UDP SecurityRuleProtocol = "Udp" + // SecurityRuleProtocolAsterisk specifies the security rule protocol + // asterisk state for security rule protocol. + SecurityRuleProtocolAsterisk SecurityRuleProtocol = "*" + // SecurityRuleProtocolTCP specifies the security rule protocol tcp state + // for security rule protocol. + SecurityRuleProtocolTCP SecurityRuleProtocol = "Tcp" + // SecurityRuleProtocolUDP specifies the security rule protocol udp state + // for security rule protocol. + SecurityRuleProtocolUDP SecurityRuleProtocol = "Udp" ) // ServiceProviderProvisioningState enumerates the values for service provider @@ -485,6 +773,15 @@ const ( // network gateway sku name ultra performance state for virtual network // gateway sku name. VirtualNetworkGatewaySkuNameUltraPerformance VirtualNetworkGatewaySkuName = "UltraPerformance" + // VirtualNetworkGatewaySkuNameVpnGw1 specifies the virtual network gateway + // sku name vpn gw 1 state for virtual network gateway sku name. + VirtualNetworkGatewaySkuNameVpnGw1 VirtualNetworkGatewaySkuName = "VpnGw1" + // VirtualNetworkGatewaySkuNameVpnGw2 specifies the virtual network gateway + // sku name vpn gw 2 state for virtual network gateway sku name. + VirtualNetworkGatewaySkuNameVpnGw2 VirtualNetworkGatewaySkuName = "VpnGw2" + // VirtualNetworkGatewaySkuNameVpnGw3 specifies the virtual network gateway + // sku name vpn gw 3 state for virtual network gateway sku name. + VirtualNetworkGatewaySkuNameVpnGw3 VirtualNetworkGatewaySkuName = "VpnGw3" ) // VirtualNetworkGatewaySkuTier enumerates the values for virtual network @@ -506,6 +803,15 @@ const ( // network gateway sku tier ultra performance state for virtual network // gateway sku tier. VirtualNetworkGatewaySkuTierUltraPerformance VirtualNetworkGatewaySkuTier = "UltraPerformance" + // VirtualNetworkGatewaySkuTierVpnGw1 specifies the virtual network gateway + // sku tier vpn gw 1 state for virtual network gateway sku tier. + VirtualNetworkGatewaySkuTierVpnGw1 VirtualNetworkGatewaySkuTier = "VpnGw1" + // VirtualNetworkGatewaySkuTierVpnGw2 specifies the virtual network gateway + // sku tier vpn gw 2 state for virtual network gateway sku tier. + VirtualNetworkGatewaySkuTierVpnGw2 VirtualNetworkGatewaySkuTier = "VpnGw2" + // VirtualNetworkGatewaySkuTierVpnGw3 specifies the virtual network gateway + // sku tier vpn gw 3 state for virtual network gateway sku tier. + VirtualNetworkGatewaySkuTierVpnGw3 VirtualNetworkGatewaySkuTier = "VpnGw3" ) // VirtualNetworkGatewayType enumerates the values for virtual network gateway @@ -521,8 +827,8 @@ const ( VirtualNetworkGatewayTypeVpn VirtualNetworkGatewayType = "Vpn" ) -// VirtualNetworkPeeringState enumerates the values for virtual network -// peering state. +// VirtualNetworkPeeringState enumerates the values for virtual network peering +// state. type VirtualNetworkPeeringState string const ( @@ -547,8 +853,8 @@ const ( RouteBased VpnType = "RouteBased" ) -// AddressSpace is addressSpace contains an array of IP address ranges that -// can be used by subnets of the virtual network. +// AddressSpace is addressSpace contains an array of IP address ranges that can +// be used by subnets of the virtual network. type AddressSpace struct { AddressPrefixes *[]string `json:"addressPrefixes,omitempty"` } @@ -581,6 +887,13 @@ type ApplicationGatewayAuthenticationCertificatePropertiesFormat struct { ProvisioningState *string `json:"provisioningState,omitempty"` } +// ApplicationGatewayAvailableWafRuleSetsResult is response for +// ApplicationGatewayAvailableWafRuleSets API service call. +type ApplicationGatewayAvailableWafRuleSetsResult struct { + autorest.Response `json:"-"` + Value *[]ApplicationGatewayFirewallRuleSet `json:"value,omitempty"` +} + // ApplicationGatewayBackendAddress is backend address of an application // gateway. type ApplicationGatewayBackendAddress struct { @@ -634,8 +947,8 @@ type ApplicationGatewayBackendHealthServer struct { Health ApplicationGatewayBackendHealthServerHealth `json:"health,omitempty"` } -// ApplicationGatewayBackendHTTPSettings is backend address pool settings of -// an application gateway. +// ApplicationGatewayBackendHTTPSettings is backend address pool settings of an +// application gateway. type ApplicationGatewayBackendHTTPSettings struct { ID *string `json:"id,omitempty"` *ApplicationGatewayBackendHTTPSettingsPropertiesFormat `json:"properties,omitempty"` @@ -653,10 +966,59 @@ type ApplicationGatewayBackendHTTPSettingsPropertiesFormat struct { Probe *SubResource `json:"probe,omitempty"` AuthenticationCertificates *[]SubResource `json:"authenticationCertificates,omitempty"` ProvisioningState *string `json:"provisioningState,omitempty"` + ConnectionDraining *ApplicationGatewayConnectionDraining `json:"connectionDraining,omitempty"` +} + +// ApplicationGatewayConnectionDraining is connection draining allows open +// connections to a backend server to be active for a specified time after the +// backend server got removed from the configuration. +type ApplicationGatewayConnectionDraining struct { + Enabled *bool `json:"enabled,omitempty"` + DrainTimeoutInSec *int32 `json:"drainTimeoutInSec,omitempty"` +} + +// ApplicationGatewayFirewallDisabledRuleGroup is allows to disable rules +// within a rule group or an entire rule group. +type ApplicationGatewayFirewallDisabledRuleGroup struct { + RuleGroupName *string `json:"ruleGroupName,omitempty"` + Rules *[]int32 `json:"rules,omitempty"` } -// ApplicationGatewayFrontendIPConfiguration is frontend IP configuration of -// an application gateway. +// ApplicationGatewayFirewallRule is a web application firewall rule. +type ApplicationGatewayFirewallRule struct { + RuleID *int32 `json:"ruleId,omitempty"` + Description *string `json:"description,omitempty"` +} + +// ApplicationGatewayFirewallRuleGroup is a web application firewall rule +// group. +type ApplicationGatewayFirewallRuleGroup struct { + RuleGroupName *string `json:"ruleGroupName,omitempty"` + Description *string `json:"description,omitempty"` + Rules *[]ApplicationGatewayFirewallRule `json:"rules,omitempty"` +} + +// ApplicationGatewayFirewallRuleSet is a web application firewall rule set. +type ApplicationGatewayFirewallRuleSet 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"` + *ApplicationGatewayFirewallRuleSetPropertiesFormat `json:"properties,omitempty"` +} + +// ApplicationGatewayFirewallRuleSetPropertiesFormat is properties of the web +// application firewall rule set. +type ApplicationGatewayFirewallRuleSetPropertiesFormat struct { + ProvisioningState *string `json:"provisioningState,omitempty"` + RuleSetType *string `json:"ruleSetType,omitempty"` + RuleSetVersion *string `json:"ruleSetVersion,omitempty"` + RuleGroups *[]ApplicationGatewayFirewallRuleGroup `json:"ruleGroups,omitempty"` +} + +// ApplicationGatewayFrontendIPConfiguration is frontend IP configuration of an +// application gateway. type ApplicationGatewayFrontendIPConfiguration struct { ID *string `json:"id,omitempty"` *ApplicationGatewayFrontendIPConfigurationPropertiesFormat `json:"properties,omitempty"` @@ -872,11 +1234,14 @@ type ApplicationGatewayURLPathMapPropertiesFormat struct { ProvisioningState *string `json:"provisioningState,omitempty"` } -// ApplicationGatewayWebApplicationFirewallConfiguration is application -// gateway web application firewall configuration. +// ApplicationGatewayWebApplicationFirewallConfiguration is application gateway +// web application firewall configuration. type ApplicationGatewayWebApplicationFirewallConfiguration struct { - Enabled *bool `json:"enabled,omitempty"` - FirewallMode ApplicationGatewayFirewallMode `json:"firewallMode,omitempty"` + Enabled *bool `json:"enabled,omitempty"` + FirewallMode ApplicationGatewayFirewallMode `json:"firewallMode,omitempty"` + RuleSetType *string `json:"ruleSetType,omitempty"` + RuleSetVersion *string `json:"ruleSetVersion,omitempty"` + DisabledRuleGroups *[]ApplicationGatewayFirewallDisabledRuleGroup `json:"disabledRuleGroups,omitempty"` } // AuthorizationListResult is response for ListAuthorizations API service call @@ -907,13 +1272,13 @@ type AuthorizationPropertiesFormat struct { } // AzureAsyncOperationResult is the response body contains the status of the -// specified asynchronous operation, indicating whether it has succeeded, is -// in progress, or has failed. Note that this status is distinct from the -// HTTP status code returned for the Get Operation Status operation itself. -// If the asynchronous operation succeeded, the response body includes the -// HTTP status code for the successful request. If the asynchronous operation -// failed, the response body includes the HTTP status code for the failed -// request and error information regarding the failure. +// specified asynchronous operation, indicating whether it has succeeded, is in +// progress, or has failed. Note that this status is distinct from the HTTP +// status code returned for the Get Operation Status operation itself. If the +// asynchronous operation succeeded, the response body includes the HTTP status +// code for the successful request. If the asynchronous operation failed, the +// response body includes the HTTP status code for the failed request and error +// information regarding the failure. type AzureAsyncOperationResult struct { Status OperationStatus `json:"status,omitempty"` Error *Error `json:"error,omitempty"` @@ -936,14 +1301,78 @@ type BackendAddressPoolPropertiesFormat struct { ProvisioningState *string `json:"provisioningState,omitempty"` } -// BgpSettings is +// BGPCommunity is contains bgp community information offered in Service +// Community resources. +type BGPCommunity struct { + ServiceSupportedRegion *string `json:"serviceSupportedRegion,omitempty"` + CommunityName *string `json:"communityName,omitempty"` + CommunityValue *string `json:"communityValue,omitempty"` + CommunityPrefixes *[]string `json:"communityPrefixes,omitempty"` +} + +// BgpPeerStatus is bGP peer status details +type BgpPeerStatus struct { + LocalAddress *string `json:"localAddress,omitempty"` + Neighbor *string `json:"neighbor,omitempty"` + Asn *int32 `json:"asn,omitempty"` + State BgpPeerState `json:"state,omitempty"` + ConnectedDuration *string `json:"connectedDuration,omitempty"` + RoutesReceived *int64 `json:"routesReceived,omitempty"` + MessagesSent *int64 `json:"messagesSent,omitempty"` + MessagesReceived *int64 `json:"messagesReceived,omitempty"` +} + +// BgpPeerStatusListResult is response for list BGP peer status API service +// call +type BgpPeerStatusListResult struct { + autorest.Response `json:"-"` + Value *[]BgpPeerStatus `json:"value,omitempty"` +} + +// BgpServiceCommunity is service Community Properties. +type BgpServiceCommunity 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"` + *BgpServiceCommunityPropertiesFormat `json:"properties,omitempty"` +} + +// BgpServiceCommunityListResult is response for the ListServiceCommunity API +// service call. +type BgpServiceCommunityListResult struct { + autorest.Response `json:"-"` + Value *[]BgpServiceCommunity `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// BgpServiceCommunityListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client BgpServiceCommunityListResult) BgpServiceCommunityListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// BgpServiceCommunityPropertiesFormat is properties of Service Community. +type BgpServiceCommunityPropertiesFormat struct { + ServiceName *string `json:"serviceName,omitempty"` + BgpCommunities *[]BGPCommunity `json:"bgpCommunities,omitempty"` +} + +// BgpSettings is bGP settings details type BgpSettings struct { Asn *int64 `json:"asn,omitempty"` BgpPeeringAddress *string `json:"bgpPeeringAddress,omitempty"` PeerWeight *int32 `json:"peerWeight,omitempty"` } -// ConnectionResetSharedKey is +// ConnectionResetSharedKey is the virtual network connection reset shared key type ConnectionResetSharedKey struct { autorest.Response `json:"-"` KeyLength *int32 `json:"keyLength,omitempty"` @@ -955,9 +1384,9 @@ type ConnectionSharedKey struct { Value *string `json:"value,omitempty"` } -// DhcpOptions is dhcpOptions contains an array of DNS servers available to -// VMs deployed in the virtual network. Standard DHCP option for a subnet -// overrides VNET DHCP options. +// DhcpOptions is dhcpOptions contains an array of DNS servers available to VMs +// deployed in the virtual network. Standard DHCP option for a subnet overrides +// VNET DHCP options. type DhcpOptions struct { DNSServers *[]string `json:"dnsServers,omitempty"` } @@ -1109,8 +1538,8 @@ type ExpressRouteCircuitPeeringConfig struct { RoutingRegistryName *string `json:"routingRegistryName,omitempty"` } -// ExpressRouteCircuitPeeringListResult is response for ListPeering API -// service call retrieves all peerings that belong to an ExpressRouteCircuit. +// ExpressRouteCircuitPeeringListResult is response for ListPeering API service +// call retrieves all peerings that belong to an ExpressRouteCircuit. type ExpressRouteCircuitPeeringListResult struct { autorest.Response `json:"-"` Value *[]ExpressRouteCircuitPeering `json:"value,omitempty"` @@ -1146,6 +1575,7 @@ type ExpressRouteCircuitPeeringPropertiesFormat struct { ProvisioningState *string `json:"provisioningState,omitempty"` GatewayManagerEtag *string `json:"gatewayManagerEtag,omitempty"` LastModifiedBy *string `json:"lastModifiedBy,omitempty"` + RouteFilter *RouteFilter `json:"routeFilter,omitempty"` } // ExpressRouteCircuitPropertiesFormat is properties of ExpressRouteCircuit. @@ -1165,11 +1595,11 @@ type ExpressRouteCircuitPropertiesFormat struct { // ExpressRouteCircuitRoutesTable is the routes table associated with the // ExpressRouteCircuit type ExpressRouteCircuitRoutesTable struct { - Network *string `json:"network,omitempty"` - NextHop *string `json:"nextHop,omitempty"` - LocPrf *string `json:"locPrf,omitempty"` - Weight *int32 `json:"weight,omitempty"` - Path *string `json:"path,omitempty"` + NetworkProperty *string `json:"network,omitempty"` + NextHop *string `json:"nextHop,omitempty"` + LocPrf *string `json:"locPrf,omitempty"` + Weight *int32 `json:"weight,omitempty"` + Path *string `json:"path,omitempty"` } // ExpressRouteCircuitRoutesTableSummary is the routes table associated with @@ -1275,6 +1705,26 @@ type ExpressRouteServiceProviderPropertiesFormat struct { ProvisioningState *string `json:"provisioningState,omitempty"` } +// FlowLogInformation is information on the configuration of flow log. +type FlowLogInformation struct { + autorest.Response `json:"-"` + TargetResourceID *string `json:"targetResourceId,omitempty"` + *FlowLogProperties `json:"properties,omitempty"` +} + +// FlowLogProperties is parameters that define the configuration of flow log. +type FlowLogProperties struct { + StorageID *string `json:"storageId,omitempty"` + Enabled *bool `json:"enabled,omitempty"` + RetentionPolicy *RetentionPolicyParameters `json:"retentionPolicy,omitempty"` +} + +// FlowLogStatusParameters is parameters that define a resource to query flow +// log status. +type FlowLogStatusParameters struct { + TargetResourceID *string `json:"targetResourceId,omitempty"` +} + // FrontendIPConfiguration is frontend IP address of the load balancer. type FrontendIPConfiguration struct { ID *string `json:"id,omitempty"` @@ -1297,6 +1747,23 @@ type FrontendIPConfigurationPropertiesFormat struct { ProvisioningState *string `json:"provisioningState,omitempty"` } +// GatewayRoute is gateway routing details +type GatewayRoute struct { + LocalAddress *string `json:"localAddress,omitempty"` + NetworkProperty *string `json:"network,omitempty"` + NextHop *string `json:"nextHop,omitempty"` + SourcePeer *string `json:"sourcePeer,omitempty"` + Origin *string `json:"origin,omitempty"` + AsPath *string `json:"asPath,omitempty"` + Weight *int32 `json:"weight,omitempty"` +} + +// GatewayRouteListResult is list of virtual network gateway routes +type GatewayRouteListResult struct { + autorest.Response `json:"-"` + Value *[]GatewayRoute `json:"value,omitempty"` +} + // InboundNatPool is inbound NAT pool of the load balancer. type InboundNatPool struct { ID *string `json:"id,omitempty"` @@ -1347,6 +1814,12 @@ type Interface struct { Etag *string `json:"etag,omitempty"` } +// InterfaceAssociation is network interface and its custom security rules. +type InterfaceAssociation struct { + ID *string `json:"id,omitempty"` + SecurityRules *[]SecurityRule `json:"securityRules,omitempty"` +} + // InterfaceDNSSettings is dNS settings of a network interface. type InterfaceDNSSettings struct { DNSServers *[]string `json:"dnsServers,omitempty"` @@ -1437,6 +1910,19 @@ type IPConfigurationPropertiesFormat struct { ProvisioningState *string `json:"provisioningState,omitempty"` } +// IpsecPolicy is an IPSec Policy configuration for a virtual network gateway +// connection +type IpsecPolicy struct { + SaLifeTimeSeconds *int32 `json:"saLifeTimeSeconds,omitempty"` + SaDataSizeKilobytes *int32 `json:"saDataSizeKilobytes,omitempty"` + IpsecEncryption IpsecEncryption `json:"ipsecEncryption,omitempty"` + IpsecIntegrity IpsecIntegrity `json:"ipsecIntegrity,omitempty"` + IkeEncryption IkeEncryption `json:"ikeEncryption,omitempty"` + IkeIntegrity IkeIntegrity `json:"ikeIntegrity,omitempty"` + DhGroup DhGroup `json:"dhGroup,omitempty"` + PfsGroup PfsGroup `json:"pfsGroup,omitempty"` +} + // LoadBalancer is loadBalancer resource type LoadBalancer struct { autorest.Response `json:"-"` @@ -1544,6 +2030,23 @@ type LocalNetworkGatewayPropertiesFormat struct { ProvisioningState *string `json:"provisioningState,omitempty"` } +// NextHopParameters is parameters that define the source and destination +// endpoint. +type NextHopParameters struct { + TargetResourceID *string `json:"targetResourceId,omitempty"` + SourceIPAddress *string `json:"sourceIPAddress,omitempty"` + DestinationIPAddress *string `json:"destinationIPAddress,omitempty"` + TargetNicResourceID *string `json:"targetNicResourceId,omitempty"` +} + +// NextHopResult is the information about next hop from the specified VM. +type NextHopResult struct { + autorest.Response `json:"-"` + NextHopType NextHopType `json:"nextHopType,omitempty"` + NextHopIPAddress *string `json:"nextHopIpAddress,omitempty"` + RouteTableID *string `json:"routeTableId,omitempty"` +} + // OutboundNatRule is outbound NAT pool of the load balancer. type OutboundNatRule struct { ID *string `json:"id,omitempty"` @@ -1560,6 +2063,97 @@ type OutboundNatRulePropertiesFormat struct { ProvisioningState *string `json:"provisioningState,omitempty"` } +// PacketCapture is parameters that define the create packet capture operation. +type PacketCapture struct { + *PacketCaptureParameters `json:"properties,omitempty"` +} + +// PacketCaptureFilter is filter that is applied to packet capture request. +// Multiple filters can be applied. +type PacketCaptureFilter struct { + Protocol PcProtocol `json:"protocol,omitempty"` + LocalIPAddress *string `json:"localIPAddress,omitempty"` + RemoteIPAddress *string `json:"remoteIPAddress,omitempty"` + LocalPort *string `json:"localPort,omitempty"` + RemotePort *string `json:"remotePort,omitempty"` +} + +// PacketCaptureListResult is list of packet capture sessions. +type PacketCaptureListResult struct { + autorest.Response `json:"-"` + Value *[]PacketCaptureResult `json:"value,omitempty"` +} + +// PacketCaptureParameters is parameters that define the create packet capture +// operation. +type PacketCaptureParameters struct { + Target *string `json:"target,omitempty"` + BytesToCapturePerPacket *int32 `json:"bytesToCapturePerPacket,omitempty"` + TotalBytesPerSession *int32 `json:"totalBytesPerSession,omitempty"` + TimeLimitInSeconds *int32 `json:"timeLimitInSeconds,omitempty"` + StorageLocation *PacketCaptureStorageLocation `json:"storageLocation,omitempty"` + Filters *[]PacketCaptureFilter `json:"filters,omitempty"` +} + +// PacketCaptureQueryStatusResult is status of packet capture session. +type PacketCaptureQueryStatusResult struct { + autorest.Response `json:"-"` + Name *string `json:"name,omitempty"` + ID *string `json:"id,omitempty"` + CaptureStartTime *date.Time `json:"captureStartTime,omitempty"` + PacketCaptureStatus PcStatus `json:"packetCaptureStatus,omitempty"` + StopReason *string `json:"stopReason,omitempty"` + PacketCaptureError *[]PcError `json:"packetCaptureError,omitempty"` +} + +// PacketCaptureResult is information about packet capture session. +type PacketCaptureResult struct { + autorest.Response `json:"-"` + Name *string `json:"name,omitempty"` + ID *string `json:"id,omitempty"` + Etag *string `json:"etag,omitempty"` + *PacketCaptureResultProperties `json:"properties,omitempty"` +} + +// PacketCaptureResultProperties is describes the properties of a packet +// capture session. +type PacketCaptureResultProperties struct { + Target *string `json:"target,omitempty"` + BytesToCapturePerPacket *int32 `json:"bytesToCapturePerPacket,omitempty"` + TotalBytesPerSession *int32 `json:"totalBytesPerSession,omitempty"` + TimeLimitInSeconds *int32 `json:"timeLimitInSeconds,omitempty"` + StorageLocation *PacketCaptureStorageLocation `json:"storageLocation,omitempty"` + Filters *[]PacketCaptureFilter `json:"filters,omitempty"` + ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` +} + +// PacketCaptureStorageLocation is describes the storage location for a packet +// capture session. +type PacketCaptureStorageLocation struct { + StorageID *string `json:"storageId,omitempty"` + StoragePath *string `json:"storagePath,omitempty"` + FilePath *string `json:"filePath,omitempty"` +} + +// PatchRouteFilter is route Filter Resource. +type PatchRouteFilter struct { + ID *string `json:"id,omitempty"` + *RouteFilterPropertiesFormat `json:"properties,omitempty"` + Name *string `json:"name,omitempty"` + Etag *string `json:"etag,omitempty"` + Type *string `json:"type,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` +} + +// PatchRouteFilterRule is route Filter Rule Resource +type PatchRouteFilterRule struct { + ID *string `json:"id,omitempty"` + *RouteFilterRulePropertiesFormat `json:"properties,omitempty"` + Name *string `json:"name,omitempty"` + Etag *string `json:"etag,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` +} + // Probe is a load balancer probe. type Probe struct { ID *string `json:"id,omitempty"` @@ -1591,8 +2185,8 @@ type PublicIPAddress struct { Etag *string `json:"etag,omitempty"` } -// PublicIPAddressDNSSettings is contains the FQDN of the DNS record -// associated with the public IP address. +// PublicIPAddressDNSSettings is contains FQDN of the DNS record associated +// with the public IP address type PublicIPAddressDNSSettings struct { DomainNameLabel *string `json:"domainNameLabel,omitempty"` Fqdn *string `json:"fqdn,omitempty"` @@ -1631,6 +2225,12 @@ type PublicIPAddressPropertiesFormat struct { ProvisioningState *string `json:"provisioningState,omitempty"` } +// QueryTroubleshootingParameters is parameters that define the resource to +// query the troubleshooting result. +type QueryTroubleshootingParameters struct { + TargetResourceID *string `json:"targetResourceId,omitempty"` +} + // Resource is type Resource struct { ID *string `json:"id,omitempty"` @@ -1655,6 +2255,13 @@ type ResourceNavigationLinkFormat struct { ProvisioningState *string `json:"provisioningState,omitempty"` } +// RetentionPolicyParameters is parameters that define the retention policy for +// flow log. +type RetentionPolicyParameters struct { + Days *int32 `json:"days,omitempty"` + Enabled *bool `json:"enabled,omitempty"` +} + // Route is route resource type Route struct { autorest.Response `json:"-"` @@ -1664,6 +2271,83 @@ type Route struct { Etag *string `json:"etag,omitempty"` } +// RouteFilter is route Filter Resource. +type RouteFilter 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"` + *RouteFilterPropertiesFormat `json:"properties,omitempty"` + Etag *string `json:"etag,omitempty"` +} + +// RouteFilterListResult is response for the ListRouteFilters API service call. +type RouteFilterListResult struct { + autorest.Response `json:"-"` + Value *[]RouteFilter `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// RouteFilterListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client RouteFilterListResult) RouteFilterListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// RouteFilterPropertiesFormat is route Filter Resource +type RouteFilterPropertiesFormat struct { + Rules *[]RouteFilterRule `json:"rules,omitempty"` + Peerings *[]ExpressRouteCircuitPeering `json:"peerings,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// RouteFilterRule is route Filter Rule Resource +type RouteFilterRule struct { + autorest.Response `json:"-"` + ID *string `json:"id,omitempty"` + *RouteFilterRulePropertiesFormat `json:"properties,omitempty"` + Name *string `json:"name,omitempty"` + Location *string `json:"location,omitempty"` + Etag *string `json:"etag,omitempty"` + Tags *map[string]*string `json:"tags,omitempty"` +} + +// RouteFilterRuleListResult is response for the ListRouteFilterRules API +// service call +type RouteFilterRuleListResult struct { + autorest.Response `json:"-"` + Value *[]RouteFilterRule `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// RouteFilterRuleListResultPreparer prepares a request to retrieve the next set of results. It returns +// nil if no more results exist. +func (client RouteFilterRuleListResult) RouteFilterRuleListResultPreparer() (*http.Request, error) { + if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(client.NextLink))) +} + +// RouteFilterRulePropertiesFormat is route Filter Rule Resource +type RouteFilterRulePropertiesFormat struct { + Access Access `json:"access,omitempty"` + RouteFilterRuleType *string `json:"routeFilterRuleType,omitempty"` + Communities *[]string `json:"communities,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + // RouteListResult is response for the ListRoute API service call type RouteListResult struct { autorest.Response `json:"-"` @@ -1761,6 +2445,13 @@ func (client SecurityGroupListResult) SecurityGroupListResultPreparer() (*http.R autorest.WithBaseURL(to.String(client.NextLink))) } +// SecurityGroupNetworkInterface is network interface and all its associated +// security rules. +type SecurityGroupNetworkInterface struct { + ID *string `json:"id,omitempty"` + SecurityRuleAssociations *SecurityRuleAssociations `json:"securityRuleAssociations,omitempty"` +} + // SecurityGroupPropertiesFormat is network Security Group resource. type SecurityGroupPropertiesFormat struct { SecurityRules *[]SecurityRule `json:"securityRules,omitempty"` @@ -1771,6 +2462,19 @@ type SecurityGroupPropertiesFormat struct { ProvisioningState *string `json:"provisioningState,omitempty"` } +// SecurityGroupViewParameters is parameters that define the VM to check +// security groups for. +type SecurityGroupViewParameters struct { + TargetResourceID *string `json:"targetResourceId,omitempty"` +} + +// SecurityGroupViewResult is the information about security rules applied to +// the specified VM. +type SecurityGroupViewResult struct { + autorest.Response `json:"-"` + NetworkInterfaces *[]SecurityGroupNetworkInterface `json:"networkInterfaces,omitempty"` +} + // SecurityRule is network security rule. type SecurityRule struct { autorest.Response `json:"-"` @@ -1780,6 +2484,15 @@ type SecurityRule struct { Etag *string `json:"etag,omitempty"` } +// SecurityRuleAssociations is all security rules associated with the network +// interface. +type SecurityRuleAssociations struct { + NetworkInterfaceAssociation *InterfaceAssociation `json:"networkInterfaceAssociation,omitempty"` + SubnetAssociation *SubnetAssociation `json:"subnetAssociation,omitempty"` + DefaultSecurityRules *[]SecurityRule `json:"defaultSecurityRules,omitempty"` + EffectiveSecurityRules *[]EffectiveNetworkSecurityRule `json:"effectiveSecurityRules,omitempty"` +} + // SecurityRuleListResult is response for ListSecurityRule API service call. // Retrieves all security rules that belongs to a network security group. type SecurityRuleListResult struct { @@ -1829,6 +2542,12 @@ type Subnet struct { Etag *string `json:"etag,omitempty"` } +// SubnetAssociation is network interface and its custom security rules. +type SubnetAssociation struct { + ID *string `json:"id,omitempty"` + SecurityRules *[]SecurityRule `json:"securityRules,omitempty"` +} + // SubnetListResult is response for ListSubnets API service callRetrieves all // subnet that belongs to a virtual network type SubnetListResult struct { @@ -1864,6 +2583,79 @@ type SubResource struct { ID *string `json:"id,omitempty"` } +// Topology is topology of the specified resource group. +type Topology struct { + autorest.Response `json:"-"` + ID *string `json:"id,omitempty"` + CreatedDateTime *date.Time `json:"createdDateTime,omitempty"` + LastModified *date.Time `json:"lastModified,omitempty"` + Resources *[]TopologyResource `json:"resources,omitempty"` +} + +// TopologyAssociation is resources that have an association with the parent +// resource. +type TopologyAssociation struct { + Name *string `json:"name,omitempty"` + ResourceID *string `json:"resourceId,omitempty"` + AssociationType AssociationType `json:"associationType,omitempty"` +} + +// TopologyParameters is parameters that define the representation of topology. +type TopologyParameters struct { + TargetResourceGroupName *string `json:"targetResourceGroupName,omitempty"` +} + +// TopologyResource is the network resource topology information for the given +// resource group. +type TopologyResource struct { + Name *string `json:"name,omitempty"` + ID *string `json:"id,omitempty"` + Location *string `json:"location,omitempty"` + Associations *[]TopologyAssociation `json:"associations,omitempty"` +} + +// TroubleshootingDetails is information gained from troubleshooting of +// specified resource. +type TroubleshootingDetails struct { + ID *string `json:"id,omitempty"` + ReasonType *string `json:"reasonType,omitempty"` + Summary *string `json:"summary,omitempty"` + Detail *string `json:"detail,omitempty"` + RecommendedActions *[]TroubleshootingRecommendedActions `json:"recommendedActions,omitempty"` +} + +// TroubleshootingParameters is parameters that define the resource to +// troubleshoot. +type TroubleshootingParameters struct { + TargetResourceID *string `json:"targetResourceId,omitempty"` + *TroubleshootingProperties `json:"properties,omitempty"` +} + +// TroubleshootingProperties is storage location provided for troubleshoot. +type TroubleshootingProperties struct { + StorageID *string `json:"storageId,omitempty"` + StoragePath *string `json:"storagePath,omitempty"` +} + +// TroubleshootingRecommendedActions is recommended actions based on discovered +// issues. +type TroubleshootingRecommendedActions struct { + ActionID *string `json:"actionId,omitempty"` + ActionText *string `json:"actionText,omitempty"` + ActionURI *string `json:"actionUri,omitempty"` + ActionURIText *string `json:"actionUriText,omitempty"` +} + +// TroubleshootingResult is troubleshooting information gained from specified +// resource. +type TroubleshootingResult struct { + autorest.Response `json:"-"` + StartTime *date.Time `json:"startTime,omitempty"` + EndTime *date.Time `json:"endTime,omitempty"` + Code *string `json:"code,omitempty"` + Results *[]TroubleshootingDetails `json:"results,omitempty"` +} + // TunnelConnectionHealth is virtualNetworkGatewayConnection properties type TunnelConnectionHealth struct { Tunnel *string `json:"tunnel,omitempty"` @@ -1906,6 +2698,27 @@ func (client UsagesListResult) UsagesListResultPreparer() (*http.Request, error) autorest.WithBaseURL(to.String(client.NextLink))) } +// VerificationIPFlowParameters is parameters that define the IP flow to be +// verified. +type VerificationIPFlowParameters struct { + TargetResourceID *string `json:"targetResourceId,omitempty"` + Direction Direction `json:"direction,omitempty"` + Protocol Protocol `json:"protocol,omitempty"` + LocalPort *string `json:"localPort,omitempty"` + RemotePort *string `json:"remotePort,omitempty"` + LocalIPAddress *string `json:"localIPAddress,omitempty"` + RemoteIPAddress *string `json:"remoteIPAddress,omitempty"` + TargetNicResourceID *string `json:"targetNicResourceId,omitempty"` +} + +// VerificationIPFlowResult is results of IP flow verification on the target +// resource. +type VerificationIPFlowResult struct { + autorest.Response `json:"-"` + Access Access `json:"access,omitempty"` + RuleName *string `json:"ruleName,omitempty"` +} + // VirtualNetwork is virtual Network resource. type VirtualNetwork struct { autorest.Response `json:"-"` @@ -1966,25 +2779,27 @@ func (client VirtualNetworkGatewayConnectionListResult) VirtualNetworkGatewayCon // VirtualNetworkGatewayConnectionPropertiesFormat is // virtualNetworkGatewayConnection properties type VirtualNetworkGatewayConnectionPropertiesFormat struct { - AuthorizationKey *string `json:"authorizationKey,omitempty"` - VirtualNetworkGateway1 *VirtualNetworkGateway `json:"virtualNetworkGateway1,omitempty"` - VirtualNetworkGateway2 *VirtualNetworkGateway `json:"virtualNetworkGateway2,omitempty"` - LocalNetworkGateway2 *LocalNetworkGateway `json:"localNetworkGateway2,omitempty"` - ConnectionType VirtualNetworkGatewayConnectionType `json:"connectionType,omitempty"` - RoutingWeight *int32 `json:"routingWeight,omitempty"` - SharedKey *string `json:"sharedKey,omitempty"` - ConnectionStatus VirtualNetworkGatewayConnectionStatus `json:"connectionStatus,omitempty"` - TunnelConnectionStatus *[]TunnelConnectionHealth `json:"tunnelConnectionStatus,omitempty"` - EgressBytesTransferred *int64 `json:"egressBytesTransferred,omitempty"` - IngressBytesTransferred *int64 `json:"ingressBytesTransferred,omitempty"` - Peer *SubResource `json:"peer,omitempty"` - EnableBgp *bool `json:"enableBgp,omitempty"` - ResourceGUID *string `json:"resourceGuid,omitempty"` - ProvisioningState *string `json:"provisioningState,omitempty"` -} - -// VirtualNetworkGatewayIPConfiguration is iP configuration for virtual -// network gateway + AuthorizationKey *string `json:"authorizationKey,omitempty"` + VirtualNetworkGateway1 *VirtualNetworkGateway `json:"virtualNetworkGateway1,omitempty"` + VirtualNetworkGateway2 *VirtualNetworkGateway `json:"virtualNetworkGateway2,omitempty"` + LocalNetworkGateway2 *LocalNetworkGateway `json:"localNetworkGateway2,omitempty"` + ConnectionType VirtualNetworkGatewayConnectionType `json:"connectionType,omitempty"` + RoutingWeight *int32 `json:"routingWeight,omitempty"` + SharedKey *string `json:"sharedKey,omitempty"` + ConnectionStatus VirtualNetworkGatewayConnectionStatus `json:"connectionStatus,omitempty"` + TunnelConnectionStatus *[]TunnelConnectionHealth `json:"tunnelConnectionStatus,omitempty"` + EgressBytesTransferred *int64 `json:"egressBytesTransferred,omitempty"` + IngressBytesTransferred *int64 `json:"ingressBytesTransferred,omitempty"` + Peer *SubResource `json:"peer,omitempty"` + EnableBgp *bool `json:"enableBgp,omitempty"` + UsePolicyBasedTrafficSelectors *bool `json:"usePolicyBasedTrafficSelectors,omitempty"` + IpsecPolicies *[]IpsecPolicy `json:"ipsecPolicies,omitempty"` + ResourceGUID *string `json:"resourceGuid,omitempty"` + ProvisioningState *string `json:"provisioningState,omitempty"` +} + +// VirtualNetworkGatewayIPConfiguration is iP configuration for virtual network +// gateway type VirtualNetworkGatewayIPConfiguration struct { ID *string `json:"id,omitempty"` *VirtualNetworkGatewayIPConfigurationPropertiesFormat `json:"properties,omitempty"` @@ -2043,8 +2858,8 @@ type VirtualNetworkGatewaySku struct { Capacity *int32 `json:"capacity,omitempty"` } -// VirtualNetworkListResult is response for the ListVirtualNetworks API -// service call. +// VirtualNetworkListResult is response for the ListVirtualNetworks API service +// call. type VirtualNetworkListResult struct { autorest.Response `json:"-"` Value *[]VirtualNetwork `json:"value,omitempty"` @@ -2120,9 +2935,9 @@ type VpnClientConfiguration struct { VpnClientRevokedCertificates *[]VpnClientRevokedCertificate `json:"vpnClientRevokedCertificates,omitempty"` } -// VpnClientParameters is vpnClientParameters +// VpnClientParameters is vpn Client Parameters for package generation type VpnClientParameters struct { - ProcessorArchitecture ProcessorArchitecture `json:"ProcessorArchitecture,omitempty"` + ProcessorArchitecture ProcessorArchitecture `json:"processorArchitecture,omitempty"` } // VpnClientRevokedCertificate is vPN client revoked certificate of virtual @@ -2134,8 +2949,8 @@ type VpnClientRevokedCertificate struct { Etag *string `json:"etag,omitempty"` } -// VpnClientRevokedCertificatePropertiesFormat is properties of the revoked -// VPN client certificate of virtual network gateway. +// VpnClientRevokedCertificatePropertiesFormat is properties of the revoked VPN +// client certificate of virtual network gateway. type VpnClientRevokedCertificatePropertiesFormat struct { Thumbprint *string `json:"thumbprint,omitempty"` ProvisioningState *string `json:"provisioningState,omitempty"` @@ -2156,3 +2971,26 @@ type VpnClientRootCertificatePropertiesFormat struct { PublicCertData *string `json:"publicCertData,omitempty"` ProvisioningState *string `json:"provisioningState,omitempty"` } + +// Watcher is network watcher in a resource group. +type Watcher 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"` + Etag *string `json:"etag,omitempty"` + *WatcherPropertiesFormat `json:"properties,omitempty"` +} + +// WatcherListResult is list of network watcher resources. +type WatcherListResult struct { + autorest.Response `json:"-"` + Value *[]Watcher `json:"value,omitempty"` +} + +// WatcherPropertiesFormat is the network watcher properties. +type WatcherPropertiesFormat struct { + ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/packetcaptures.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/packetcaptures.go new file mode 100755 index 000000000000..fbeb0d9ef4b1 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/packetcaptures.go @@ -0,0 +1,526 @@ +package network + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// PacketCapturesClient is the composite Swagger for Network Client +type PacketCapturesClient struct { + ManagementClient +} + +// NewPacketCapturesClient creates an instance of the PacketCapturesClient +// client. +func NewPacketCapturesClient(subscriptionID string) PacketCapturesClient { + return NewPacketCapturesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewPacketCapturesClientWithBaseURI creates an instance of the +// PacketCapturesClient client. +func NewPacketCapturesClientWithBaseURI(baseURI string, subscriptionID string) PacketCapturesClient { + return PacketCapturesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Create create and start a packet capture on the specified VM. 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. networkWatcherName is +// the name of the network watcher. packetCaptureName is the name of the packet +// capture session. parameters is parameters that define the create packet +// capture operation. +func (client PacketCapturesClient) Create(resourceGroupName string, networkWatcherName string, packetCaptureName string, parameters PacketCapture, cancel <-chan struct{}) (<-chan PacketCaptureResult, <-chan error) { + resultChan := make(chan PacketCaptureResult, 1) + errChan := make(chan error, 1) + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.PacketCaptureParameters", Name: validation.Null, Rule: true, + Chain: []validation.Constraint{{Target: "parameters.PacketCaptureParameters.Target", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.PacketCaptureParameters.StorageLocation", Name: validation.Null, Rule: true, Chain: nil}, + }}}}}); err != nil { + errChan <- validation.NewErrorWithValidationError(err, "network.PacketCapturesClient", "Create") + close(errChan) + close(resultChan) + return resultChan, errChan + } + + go func() { + var err error + var result PacketCaptureResult + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.CreatePreparer(resourceGroupName, networkWatcherName, packetCaptureName, parameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "Create", nil, "Failure preparing request") + return + } + + resp, err := client.CreateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "Create", resp, "Failure sending request") + return + } + + result, err = client.CreateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "Create", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// CreatePreparer prepares the Create request. +func (client PacketCapturesClient) CreatePreparer(resourceGroupName string, networkWatcherName string, packetCaptureName string, parameters PacketCapture, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "networkWatcherName": autorest.Encode("path", networkWatcherName), + "packetCaptureName": autorest.Encode("path", packetCaptureName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// CreateSender sends the Create request. The method will close the +// http.Response Body if it receives an error. +func (client PacketCapturesClient) CreateSender(req *http.Request) (*http.Response, error) { + 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 PacketCapturesClient) CreateResponder(resp *http.Response) (result PacketCaptureResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes the specified packet capture session. 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. networkWatcherName is +// the name of the network watcher. packetCaptureName is the name of the packet +// capture session. +func (client PacketCapturesClient) Delete(resourceGroupName string, networkWatcherName string, packetCaptureName string, cancel <-chan struct{}) (<-chan autorest.Response, <-chan error) { + resultChan := make(chan autorest.Response, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result autorest.Response + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeletePreparer(resourceGroupName, networkWatcherName, packetCaptureName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "Delete", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// DeletePreparer prepares the Delete request. +func (client PacketCapturesClient) DeletePreparer(resourceGroupName string, networkWatcherName string, packetCaptureName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "networkWatcherName": autorest.Encode("path", networkWatcherName), + "packetCaptureName": autorest.Encode("path", packetCaptureName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client PacketCapturesClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client PacketCapturesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent, http.StatusAccepted), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets a packet capture session by name. +// +// resourceGroupName is the name of the resource group. networkWatcherName is +// the name of the network watcher. packetCaptureName is the name of the packet +// capture session. +func (client PacketCapturesClient) Get(resourceGroupName string, networkWatcherName string, packetCaptureName string) (result PacketCaptureResult, err error) { + req, err := client.GetPreparer(resourceGroupName, networkWatcherName, packetCaptureName) + if err != nil { + err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client PacketCapturesClient) GetPreparer(resourceGroupName string, networkWatcherName string, packetCaptureName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "networkWatcherName": autorest.Encode("path", networkWatcherName), + "packetCaptureName": autorest.Encode("path", packetCaptureName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client PacketCapturesClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client PacketCapturesClient) GetResponder(resp *http.Response) (result PacketCaptureResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetStatus query the status of a running packet capture session. 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. networkWatcherName is +// the name of the Network Watcher resource. packetCaptureName is the name +// given to the packet capture session. +func (client PacketCapturesClient) GetStatus(resourceGroupName string, networkWatcherName string, packetCaptureName string, cancel <-chan struct{}) (<-chan PacketCaptureQueryStatusResult, <-chan error) { + resultChan := make(chan PacketCaptureQueryStatusResult, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result PacketCaptureQueryStatusResult + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.GetStatusPreparer(resourceGroupName, networkWatcherName, packetCaptureName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "GetStatus", nil, "Failure preparing request") + return + } + + resp, err := client.GetStatusSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "GetStatus", resp, "Failure sending request") + return + } + + result, err = client.GetStatusResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "GetStatus", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// GetStatusPreparer prepares the GetStatus request. +func (client PacketCapturesClient) GetStatusPreparer(resourceGroupName string, networkWatcherName string, packetCaptureName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "networkWatcherName": autorest.Encode("path", networkWatcherName), + "packetCaptureName": autorest.Encode("path", packetCaptureName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}/queryStatus", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// GetStatusSender sends the GetStatus request. The method will close the +// http.Response Body if it receives an error. +func (client PacketCapturesClient) GetStatusSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// GetStatusResponder handles the response to the GetStatus request. The method always +// closes the http.Response Body. +func (client PacketCapturesClient) GetStatusResponder(resp *http.Response) (result PacketCaptureQueryStatusResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List lists all packet capture sessions within the specified resource group. +// +// resourceGroupName is the name of the resource group. networkWatcherName is +// the name of the Network Watcher resource. +func (client PacketCapturesClient) List(resourceGroupName string, networkWatcherName string) (result PacketCaptureListResult, err error) { + req, err := client.ListPreparer(resourceGroupName, networkWatcherName) + if err != nil { + err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "List", resp, "Failure sending request") + return + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client PacketCapturesClient) ListPreparer(resourceGroupName string, networkWatcherName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "networkWatcherName": autorest.Encode("path", networkWatcherName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client PacketCapturesClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client PacketCapturesClient) ListResponder(resp *http.Response) (result PacketCaptureListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Stop stops a specified packet capture session. 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. networkWatcherName is +// the name of the network watcher. packetCaptureName is the name of the packet +// capture session. +func (client PacketCapturesClient) Stop(resourceGroupName string, networkWatcherName string, packetCaptureName string, cancel <-chan struct{}) (<-chan autorest.Response, <-chan error) { + resultChan := make(chan autorest.Response, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result autorest.Response + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.StopPreparer(resourceGroupName, networkWatcherName, packetCaptureName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "Stop", nil, "Failure preparing request") + return + } + + resp, err := client.StopSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "Stop", resp, "Failure sending request") + return + } + + result, err = client.StopResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.PacketCapturesClient", "Stop", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// StopPreparer prepares the Stop request. +func (client PacketCapturesClient) StopPreparer(resourceGroupName string, networkWatcherName string, packetCaptureName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "networkWatcherName": autorest.Encode("path", networkWatcherName), + "packetCaptureName": autorest.Encode("path", packetCaptureName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}/stop", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// StopSender sends the Stop request. The method will close the +// http.Response Body if it receives an error. +func (client PacketCapturesClient) StopSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// StopResponder handles the response to the Stop request. The method always +// closes the http.Response Body. +func (client PacketCapturesClient) StopResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + 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/publicipaddresses.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/publicipaddresses.go old mode 100644 new mode 100755 index d8ef099a79cb..896bc817d91e --- 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,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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -25,11 +25,7 @@ import ( "net/http" ) -// PublicIPAddressesClient 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 resources. The API has entities -// that capture the relationship between an end user and the Microsoft Azure -// Networks service. +// PublicIPAddressesClient is the composite Swagger for Network Client type PublicIPAddressesClient struct { ManagementClient } @@ -47,59 +43,58 @@ func NewPublicIPAddressesClientWithBaseURI(baseURI string, subscriptionID string } // CreateOrUpdate creates or updates a static or dynamic public IP 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. +// 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 public IP address. parameters is parameters supplied to -// the create or update public IP address operation. -func (client PublicIPAddressesClient) CreateOrUpdate(resourceGroupName string, publicIPAddressName string, parameters PublicIPAddress, cancel <-chan struct{}) (result autorest.Response, err error) { +// the name of the public IP address. parameters is parameters supplied to the +// create or update public IP address operation. +func (client PublicIPAddressesClient) CreateOrUpdate(resourceGroupName string, publicIPAddressName string, parameters PublicIPAddress, cancel <-chan struct{}) (<-chan PublicIPAddress, <-chan error) { + resultChan := make(chan PublicIPAddress, 1) + errChan := make(chan error, 1) if err := validation.Validate([]validation.Validation{ {TargetValue: parameters, Constraints: []validation.Constraint{{Target: "parameters.PublicIPAddressPropertiesFormat", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "parameters.PublicIPAddressPropertiesFormat.IPConfiguration", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "parameters.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat.Subnet", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat.Subnet.SubnetPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat.Subnet.SubnetPropertiesFormat.NetworkSecurityGroup", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat.Subnet.SubnetPropertiesFormat.NetworkSecurityGroup.SecurityGroupPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat.Subnet.SubnetPropertiesFormat.NetworkSecurityGroup.SecurityGroupPropertiesFormat.NetworkInterfaces", Name: validation.ReadOnly, Rule: true, Chain: nil}, - {Target: "parameters.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat.Subnet.SubnetPropertiesFormat.NetworkSecurityGroup.SecurityGroupPropertiesFormat.Subnets", Name: validation.ReadOnly, Rule: true, Chain: nil}, - }}, - }}, - {Target: "parameters.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat.Subnet.SubnetPropertiesFormat.RouteTable", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat.Subnet.SubnetPropertiesFormat.RouteTable.RouteTablePropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat.Subnet.SubnetPropertiesFormat.RouteTable.RouteTablePropertiesFormat.Subnets", Name: validation.ReadOnly, Rule: true, Chain: nil}}}, - }}, - {Target: "parameters.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat.Subnet.SubnetPropertiesFormat.IPConfigurations", Name: validation.ReadOnly, Rule: true, Chain: nil}, - }}, - }}, - {Target: "parameters.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}, - }}, + Chain: []validation.Constraint{{Target: "parameters.PublicIPAddressPropertiesFormat.IPConfiguration.IPConfigurationPropertiesFormat.PublicIPAddress", Name: validation.Null, Rule: false, Chain: nil}}}, }}, - {Target: "parameters.PublicIPAddressPropertiesFormat.IPConfiguration", Name: validation.ReadOnly, Rule: true, Chain: nil}, }}}}}); err != nil { - return result, validation.NewErrorWithValidationError(err, "network.PublicIPAddressesClient", "CreateOrUpdate") - } - - req, err := client.CreateOrUpdatePreparer(resourceGroupName, publicIPAddressName, parameters, cancel) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "CreateOrUpdate", nil, "Failure preparing request") - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "CreateOrUpdate", resp, "Failure sending request") - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "CreateOrUpdate", resp, "Failure responding to request") - } - - return + errChan <- validation.NewErrorWithValidationError(err, "network.PublicIPAddressesClient", "CreateOrUpdate") + close(errChan) + close(resultChan) + return resultChan, errChan + } + + go func() { + var err error + var result PublicIPAddress + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.CreateOrUpdatePreparer(resourceGroupName, publicIPAddressName, parameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "CreateOrUpdate", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. @@ -110,8 +105,9 @@ func (client PublicIPAddressesClient) CreateOrUpdatePreparer(resourceGroupName s "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -134,41 +130,55 @@ func (client PublicIPAddressesClient) CreateOrUpdateSender(req *http.Request) (* // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client PublicIPAddressesClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { +func (client PublicIPAddressesClient) CreateOrUpdateResponder(resp *http.Response) (result PublicIPAddress, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } // Delete deletes the specified public IP 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. +// 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, 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", nil, "Failure preparing request") - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Delete", resp, "Failure sending request") - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Delete", resp, "Failure responding to request") - } - - return +func (client PublicIPAddressesClient) Delete(resourceGroupName string, publicIPAddressName string, cancel <-chan struct{}) (<-chan autorest.Response, <-chan error) { + resultChan := make(chan autorest.Response, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result autorest.Response + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeletePreparer(resourceGroupName, publicIPAddressName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Delete", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // DeletePreparer prepares the Delete request. @@ -179,8 +189,9 @@ func (client PublicIPAddressesClient) DeletePreparer(resourceGroupName string, p "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -218,13 +229,15 @@ func (client PublicIPAddressesClient) DeleteResponder(resp *http.Response) (resu 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Get", nil, "Failure preparing request") + return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Get", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "Get", resp, "Failure sending request") + return } result, err = client.GetResponder(resp) @@ -243,8 +256,9 @@ func (client PublicIPAddressesClient) GetPreparer(resourceGroupName string, publ "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } if len(expand) > 0 { queryParameters["$expand"] = autorest.Encode("query", expand) @@ -283,13 +297,15 @@ func (client PublicIPAddressesClient) GetResponder(resp *http.Response) (result 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "List", nil, "Failure preparing request") + return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "List", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "List", resp, "Failure sending request") + return } result, err = client.ListResponder(resp) @@ -307,8 +323,9 @@ func (client PublicIPAddressesClient) ListPreparer(resourceGroupName string) (*h "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -366,13 +383,15 @@ func (client PublicIPAddressesClient) ListNextResults(lastResults PublicIPAddres func (client PublicIPAddressesClient) ListAll() (result PublicIPAddressListResult, err error) { req, err := client.ListAllPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListAll", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListAll", nil, "Failure preparing request") + return } resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListAll", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.PublicIPAddressesClient", "ListAll", resp, "Failure sending request") + return } result, err = client.ListAllResponder(resp) @@ -389,8 +408,9 @@ func (client PublicIPAddressesClient) ListAllPreparer() (*http.Request, error) { "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/routefilterrules.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/routefilterrules.go new file mode 100755 index 000000000000..378a75bb2f12 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/routefilterrules.go @@ -0,0 +1,468 @@ +package network + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// RouteFilterRulesClient is the composite Swagger for Network Client +type RouteFilterRulesClient struct { + ManagementClient +} + +// NewRouteFilterRulesClient creates an instance of the RouteFilterRulesClient +// client. +func NewRouteFilterRulesClient(subscriptionID string) RouteFilterRulesClient { + return NewRouteFilterRulesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewRouteFilterRulesClientWithBaseURI creates an instance of the +// RouteFilterRulesClient client. +func NewRouteFilterRulesClientWithBaseURI(baseURI string, subscriptionID string) RouteFilterRulesClient { + return RouteFilterRulesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate creates or updates a route in the specified route filter. +// 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. routeFilterName is the +// name of the route filter. ruleName is the name of the route filter rule. +// routeFilterRuleParameters is parameters supplied to the create or update +// route filter rule operation. +func (client RouteFilterRulesClient) CreateOrUpdate(resourceGroupName string, routeFilterName string, ruleName string, routeFilterRuleParameters RouteFilterRule, cancel <-chan struct{}) (<-chan RouteFilterRule, <-chan error) { + resultChan := make(chan RouteFilterRule, 1) + errChan := make(chan error, 1) + if err := validation.Validate([]validation.Validation{ + {TargetValue: routeFilterRuleParameters, + Constraints: []validation.Constraint{{Target: "routeFilterRuleParameters.RouteFilterRulePropertiesFormat", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "routeFilterRuleParameters.RouteFilterRulePropertiesFormat.RouteFilterRuleType", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "routeFilterRuleParameters.RouteFilterRulePropertiesFormat.Communities", Name: validation.Null, Rule: true, Chain: nil}, + }}}}}); err != nil { + errChan <- validation.NewErrorWithValidationError(err, "network.RouteFilterRulesClient", "CreateOrUpdate") + close(errChan) + close(resultChan) + return resultChan, errChan + } + + go func() { + var err error + var result RouteFilterRule + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.CreateOrUpdatePreparer(resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "CreateOrUpdate", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client RouteFilterRulesClient) CreateOrUpdatePreparer(resourceGroupName string, routeFilterName string, ruleName string, routeFilterRuleParameters RouteFilterRule, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "routeFilterName": autorest.Encode("path", routeFilterName), + "ruleName": autorest.Encode("path", ruleName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}", pathParameters), + autorest.WithJSON(routeFilterRuleParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client RouteFilterRulesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + 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 RouteFilterRulesClient) CreateOrUpdateResponder(resp *http.Response) (result RouteFilterRule, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes the specified rule from a route filter. 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. routeFilterName is the +// name of the route filter. ruleName is the name of the rule. +func (client RouteFilterRulesClient) Delete(resourceGroupName string, routeFilterName string, ruleName string, cancel <-chan struct{}) (<-chan autorest.Response, <-chan error) { + resultChan := make(chan autorest.Response, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result autorest.Response + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeletePreparer(resourceGroupName, routeFilterName, ruleName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "Delete", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// DeletePreparer prepares the Delete request. +func (client RouteFilterRulesClient) DeletePreparer(resourceGroupName string, routeFilterName string, ruleName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "routeFilterName": autorest.Encode("path", routeFilterName), + "ruleName": autorest.Encode("path", ruleName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client RouteFilterRulesClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client RouteFilterRulesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets the specified rule from a route filter. +// +// resourceGroupName is the name of the resource group. routeFilterName is the +// name of the route filter. ruleName is the name of the rule. +func (client RouteFilterRulesClient) Get(resourceGroupName string, routeFilterName string, ruleName string) (result RouteFilterRule, err error) { + req, err := client.GetPreparer(resourceGroupName, routeFilterName, ruleName) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client RouteFilterRulesClient) GetPreparer(resourceGroupName string, routeFilterName string, ruleName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "routeFilterName": autorest.Encode("path", routeFilterName), + "ruleName": autorest.Encode("path", ruleName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client RouteFilterRulesClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client RouteFilterRulesClient) GetResponder(resp *http.Response) (result RouteFilterRule, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByRouteFilter gets all RouteFilterRules in a route filter. +// +// resourceGroupName is the name of the resource group. routeFilterName is the +// name of the route filter. +func (client RouteFilterRulesClient) ListByRouteFilter(resourceGroupName string, routeFilterName string) (result RouteFilterRuleListResult, err error) { + req, err := client.ListByRouteFilterPreparer(resourceGroupName, routeFilterName) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "ListByRouteFilter", nil, "Failure preparing request") + return + } + + resp, err := client.ListByRouteFilterSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "ListByRouteFilter", resp, "Failure sending request") + return + } + + result, err = client.ListByRouteFilterResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "ListByRouteFilter", resp, "Failure responding to request") + } + + return +} + +// ListByRouteFilterPreparer prepares the ListByRouteFilter request. +func (client RouteFilterRulesClient) ListByRouteFilterPreparer(resourceGroupName string, routeFilterName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "routeFilterName": autorest.Encode("path", routeFilterName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListByRouteFilterSender sends the ListByRouteFilter request. The method will close the +// http.Response Body if it receives an error. +func (client RouteFilterRulesClient) ListByRouteFilterSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListByRouteFilterResponder handles the response to the ListByRouteFilter request. The method always +// closes the http.Response Body. +func (client RouteFilterRulesClient) ListByRouteFilterResponder(resp *http.Response) (result RouteFilterRuleListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByRouteFilterNextResults retrieves the next set of results, if any. +func (client RouteFilterRulesClient) ListByRouteFilterNextResults(lastResults RouteFilterRuleListResult) (result RouteFilterRuleListResult, err error) { + req, err := lastResults.RouteFilterRuleListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "ListByRouteFilter", nil, "Failure preparing next results request") + } + if req == nil { + return + } + + resp, err := client.ListByRouteFilterSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "ListByRouteFilter", resp, "Failure sending next results request") + } + + result, err = client.ListByRouteFilterResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "ListByRouteFilter", resp, "Failure responding to next results request") + } + + return +} + +// Update updates a route in the specified route filter. 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. routeFilterName is the +// name of the route filter. ruleName is the name of the route filter rule. +// routeFilterRuleParameters is parameters supplied to the update route filter +// rule operation. +func (client RouteFilterRulesClient) Update(resourceGroupName string, routeFilterName string, ruleName string, routeFilterRuleParameters PatchRouteFilterRule, cancel <-chan struct{}) (<-chan RouteFilterRule, <-chan error) { + resultChan := make(chan RouteFilterRule, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result RouteFilterRule + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.UpdatePreparer(resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "Update", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "Update", resp, "Failure sending request") + return + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteFilterRulesClient", "Update", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// UpdatePreparer prepares the Update request. +func (client RouteFilterRulesClient) UpdatePreparer(resourceGroupName string, routeFilterName string, ruleName string, routeFilterRuleParameters PatchRouteFilterRule, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "routeFilterName": autorest.Encode("path", routeFilterName), + "ruleName": autorest.Encode("path", ruleName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}", pathParameters), + autorest.WithJSON(routeFilterRuleParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// UpdateSender sends the Update request. The method will close the +// http.Response Body if it receives an error. +func (client RouteFilterRulesClient) UpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client RouteFilterRulesClient) UpdateResponder(resp *http.Response) (result RouteFilterRule, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/routefilters.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/routefilters.go new file mode 100755 index 000000000000..860ccae5c394 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/routefilters.go @@ -0,0 +1,535 @@ +package network + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// RouteFiltersClient is the composite Swagger for Network Client +type RouteFiltersClient struct { + ManagementClient +} + +// NewRouteFiltersClient creates an instance of the RouteFiltersClient client. +func NewRouteFiltersClient(subscriptionID string) RouteFiltersClient { + return NewRouteFiltersClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewRouteFiltersClientWithBaseURI creates an instance of the +// RouteFiltersClient client. +func NewRouteFiltersClientWithBaseURI(baseURI string, subscriptionID string) RouteFiltersClient { + return RouteFiltersClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate creates or updates a route filter in a 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. routeFilterName is the +// name of the route filter. routeFilterParameters is parameters supplied to +// the create or update route filter operation. +func (client RouteFiltersClient) CreateOrUpdate(resourceGroupName string, routeFilterName string, routeFilterParameters RouteFilter, cancel <-chan struct{}) (<-chan RouteFilter, <-chan error) { + resultChan := make(chan RouteFilter, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result RouteFilter + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.CreateOrUpdatePreparer(resourceGroupName, routeFilterName, routeFilterParameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "CreateOrUpdate", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client RouteFiltersClient) CreateOrUpdatePreparer(resourceGroupName string, routeFilterName string, routeFilterParameters RouteFilter, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "routeFilterName": autorest.Encode("path", routeFilterName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}", pathParameters), + autorest.WithJSON(routeFilterParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client RouteFiltersClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + 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 RouteFiltersClient) CreateOrUpdateResponder(resp *http.Response) (result RouteFilter, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes the specified route filter. 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. routeFilterName is the +// name of the route filter. +func (client RouteFiltersClient) Delete(resourceGroupName string, routeFilterName string, cancel <-chan struct{}) (<-chan autorest.Response, <-chan error) { + resultChan := make(chan autorest.Response, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result autorest.Response + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeletePreparer(resourceGroupName, routeFilterName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "Delete", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// DeletePreparer prepares the Delete request. +func (client RouteFiltersClient) DeletePreparer(resourceGroupName string, routeFilterName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "routeFilterName": autorest.Encode("path", routeFilterName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client RouteFiltersClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client RouteFiltersClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets the specified route filter. +// +// resourceGroupName is the name of the resource group. routeFilterName is the +// name of the route filter. expand is expands referenced express route bgp +// peering resources. +func (client RouteFiltersClient) Get(resourceGroupName string, routeFilterName string, expand string) (result RouteFilter, err error) { + req, err := client.GetPreparer(resourceGroupName, routeFilterName, expand) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client RouteFiltersClient) GetPreparer(resourceGroupName string, routeFilterName string, expand string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "routeFilterName": autorest.Encode("path", routeFilterName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(expand) > 0 { + queryParameters["$expand"] = autorest.Encode("query", expand) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client RouteFiltersClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client RouteFiltersClient) GetResponder(resp *http.Response) (result RouteFilter, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List gets all route filters in a subscription. +func (client RouteFiltersClient) List() (result RouteFilterListResult, err error) { + req, err := client.ListPreparer() + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "List", resp, "Failure sending request") + return + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client RouteFiltersClient) ListPreparer() (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/routeFilters", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client RouteFiltersClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client RouteFiltersClient) ListResponder(resp *http.Response) (result RouteFilterListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListNextResults retrieves the next set of results, if any. +func (client RouteFiltersClient) ListNextResults(lastResults RouteFilterListResult) (result RouteFilterListResult, err error) { + req, err := lastResults.RouteFilterListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.RouteFiltersClient", "List", nil, "Failure preparing next results request") + } + if req == nil { + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.RouteFiltersClient", "List", resp, "Failure sending next results request") + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "List", resp, "Failure responding to next results request") + } + + return +} + +// ListByResourceGroup gets all route filters in a resource group. +// +// resourceGroupName is the name of the resource group. +func (client RouteFiltersClient) ListByResourceGroup(resourceGroupName string) (result RouteFilterListResult, err error) { + req, err := client.ListByResourceGroupPreparer(resourceGroupName) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "ListByResourceGroup", resp, "Failure sending request") + return + } + + result, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "ListByResourceGroup", resp, "Failure responding to request") + } + + return +} + +// ListByResourceGroupPreparer prepares the ListByResourceGroup request. +func (client RouteFiltersClient) ListByResourceGroupPreparer(resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the +// http.Response Body if it receives an error. +func (client RouteFiltersClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always +// closes the http.Response Body. +func (client RouteFiltersClient) ListByResourceGroupResponder(resp *http.Response) (result RouteFilterListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByResourceGroupNextResults retrieves the next set of results, if any. +func (client RouteFiltersClient) ListByResourceGroupNextResults(lastResults RouteFilterListResult) (result RouteFilterListResult, err error) { + req, err := lastResults.RouteFilterListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "network.RouteFiltersClient", "ListByResourceGroup", nil, "Failure preparing next results request") + } + if req == nil { + return + } + + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "network.RouteFiltersClient", "ListByResourceGroup", resp, "Failure sending next results request") + } + + result, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "ListByResourceGroup", resp, "Failure responding to next results request") + } + + return +} + +// Update updates a route filter in a 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. routeFilterName is the +// name of the route filter. routeFilterParameters is parameters supplied to +// the update route filter operation. +func (client RouteFiltersClient) Update(resourceGroupName string, routeFilterName string, routeFilterParameters PatchRouteFilter, cancel <-chan struct{}) (<-chan RouteFilter, <-chan error) { + resultChan := make(chan RouteFilter, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result RouteFilter + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.UpdatePreparer(resourceGroupName, routeFilterName, routeFilterParameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "Update", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "Update", resp, "Failure sending request") + return + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteFiltersClient", "Update", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// UpdatePreparer prepares the Update request. +func (client RouteFiltersClient) UpdatePreparer(resourceGroupName string, routeFilterName string, routeFilterParameters PatchRouteFilter, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "routeFilterName": autorest.Encode("path", routeFilterName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}", pathParameters), + autorest.WithJSON(routeFilterParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// UpdateSender sends the Update request. The method will close the +// http.Response Body if it receives an error. +func (client RouteFiltersClient) UpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client RouteFiltersClient) UpdateResponder(resp *http.Response) (result RouteFilter, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/routes.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/routes.go old mode 100644 new mode 100755 index 9aa1cf5054dc..1366d3c14472 --- 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,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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -24,11 +24,7 @@ import ( "net/http" ) -// RoutesClient 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 resources. The API has entities that -// capture the relationship between an end user and the Microsoft Azure -// Networks service. +// RoutesClient is the composite Swagger for Network Client type RoutesClient struct { ManagementClient } @@ -43,33 +39,45 @@ func NewRoutesClientWithBaseURI(baseURI string, subscriptionID string) RoutesCli return RoutesClient{NewWithBaseURI(baseURI, subscriptionID)} } -// CreateOrUpdate creates or updates a route in the 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. +// CreateOrUpdate creates or updates a route in the 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 or update route -// operation. -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", nil, "Failure preparing request") - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.RoutesClient", "CreateOrUpdate", resp, "Failure sending request") - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutesClient", "CreateOrUpdate", resp, "Failure responding to request") - } - - return +// name of the route table. routeName is the name of the route. routeParameters +// is parameters supplied to the create or update route operation. +func (client RoutesClient) CreateOrUpdate(resourceGroupName string, routeTableName string, routeName string, routeParameters Route, cancel <-chan struct{}) (<-chan Route, <-chan error) { + resultChan := make(chan Route, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result Route + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.CreateOrUpdatePreparer(resourceGroupName, routeTableName, routeName, routeParameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RoutesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.RoutesClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RoutesClient", "CreateOrUpdate", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. @@ -81,8 +89,9 @@ func (client RoutesClient) CreateOrUpdatePreparer(resourceGroupName string, rout "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -105,13 +114,14 @@ func (client RoutesClient) CreateOrUpdateSender(req *http.Request) (*http.Respon // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client RoutesClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { +func (client RoutesClient) CreateOrUpdateResponder(resp *http.Response) (result Route, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } @@ -122,24 +132,37 @@ func (client RoutesClient) CreateOrUpdateResponder(resp *http.Response) (result // // 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, 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", nil, "Failure preparing request") - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.RoutesClient", "Delete", resp, "Failure sending request") - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RoutesClient", "Delete", resp, "Failure responding to request") - } - - return +func (client RoutesClient) Delete(resourceGroupName string, routeTableName string, routeName string, cancel <-chan struct{}) (<-chan autorest.Response, <-chan error) { + resultChan := make(chan autorest.Response, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result autorest.Response + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeletePreparer(resourceGroupName, routeTableName, routeName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RoutesClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "network.RoutesClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RoutesClient", "Delete", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // DeletePreparer prepares the Delete request. @@ -151,8 +174,9 @@ func (client RoutesClient) DeletePreparer(resourceGroupName string, routeTableNa "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -190,13 +214,15 @@ func (client RoutesClient) DeleteResponder(resp *http.Response) (result autorest 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.RoutesClient", "Get", nil, "Failure preparing request") + return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.RoutesClient", "Get", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.RoutesClient", "Get", resp, "Failure sending request") + return } result, err = client.GetResponder(resp) @@ -216,8 +242,9 @@ func (client RoutesClient) GetPreparer(resourceGroupName string, routeTableName "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -254,13 +281,15 @@ func (client RoutesClient) GetResponder(resp *http.Response) (result Route, err 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.RoutesClient", "List", nil, "Failure preparing request") + return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.RoutesClient", "List", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.RoutesClient", "List", resp, "Failure sending request") + return } result, err = client.ListResponder(resp) @@ -279,8 +308,9 @@ func (client RoutesClient) ListPreparer(resourceGroupName string, routeTableName "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( 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 old mode 100644 new mode 100755 index b53e94ebaab4..80339f207869 --- 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,22 +14,17 @@ 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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" "net/http" ) -// RouteTablesClient 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 resources. The API has entities -// that capture the relationship between an end user and the Microsoft Azure -// Networks service. +// RouteTablesClient is the composite Swagger for Network Client type RouteTablesClient struct { ManagementClient } @@ -39,8 +34,8 @@ func NewRouteTablesClient(subscriptionID string) RouteTablesClient { return NewRouteTablesClientWithBaseURI(DefaultBaseURI, subscriptionID) } -// NewRouteTablesClientWithBaseURI creates an instance of the -// RouteTablesClient client. +// NewRouteTablesClientWithBaseURI creates an instance of the RouteTablesClient +// client. func NewRouteTablesClientWithBaseURI(baseURI string, subscriptionID string) RouteTablesClient { return RouteTablesClient{NewWithBaseURI(baseURI, subscriptionID)} } @@ -51,33 +46,39 @@ func NewRouteTablesClientWithBaseURI(baseURI string, subscriptionID string) Rout // 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 -// or update route table operation. -func (client RouteTablesClient) CreateOrUpdate(resourceGroupName string, routeTableName string, parameters RouteTable, cancel <-chan struct{}) (result autorest.Response, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.RouteTablePropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.RouteTablePropertiesFormat.Subnets", Name: validation.ReadOnly, Rule: true, Chain: nil}}}}}}); err != nil { - return result, validation.NewErrorWithValidationError(err, "network.RouteTablesClient", "CreateOrUpdate") - } - - req, err := client.CreateOrUpdatePreparer(resourceGroupName, routeTableName, parameters, cancel) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "CreateOrUpdate", nil, "Failure preparing request") - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "CreateOrUpdate", resp, "Failure sending request") - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "CreateOrUpdate", resp, "Failure responding to request") - } - - return +// name of the route table. parameters is parameters supplied to the create or +// update route table operation. +func (client RouteTablesClient) CreateOrUpdate(resourceGroupName string, routeTableName string, parameters RouteTable, cancel <-chan struct{}) (<-chan RouteTable, <-chan error) { + resultChan := make(chan RouteTable, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result RouteTable + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.CreateOrUpdatePreparer(resourceGroupName, routeTableName, parameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "CreateOrUpdate", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. @@ -88,8 +89,9 @@ func (client RouteTablesClient) CreateOrUpdatePreparer(resourceGroupName string, "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -112,41 +114,55 @@ func (client RouteTablesClient) CreateOrUpdateSender(req *http.Request) (*http.R // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client RouteTablesClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { +func (client RouteTablesClient) CreateOrUpdateResponder(resp *http.Response) (result RouteTable, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } // Delete deletes the 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. +// 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, 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", nil, "Failure preparing request") - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "Delete", resp, "Failure sending request") - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "Delete", resp, "Failure responding to request") - } - - return +func (client RouteTablesClient) Delete(resourceGroupName string, routeTableName string, cancel <-chan struct{}) (<-chan autorest.Response, <-chan error) { + resultChan := make(chan autorest.Response, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result autorest.Response + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeletePreparer(resourceGroupName, routeTableName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "Delete", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // DeletePreparer prepares the Delete request. @@ -157,8 +173,9 @@ func (client RouteTablesClient) DeletePreparer(resourceGroupName string, routeTa "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -196,13 +213,15 @@ func (client RouteTablesClient) DeleteResponder(resp *http.Response) (result aut 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "Get", nil, "Failure preparing request") + return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "Get", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "Get", resp, "Failure sending request") + return } result, err = client.GetResponder(resp) @@ -221,8 +240,9 @@ func (client RouteTablesClient) GetPreparer(resourceGroupName string, routeTable "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } if len(expand) > 0 { queryParameters["$expand"] = autorest.Encode("query", expand) @@ -261,13 +281,15 @@ func (client RouteTablesClient) GetResponder(resp *http.Response) (result RouteT 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "List", nil, "Failure preparing request") + return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "List", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "List", resp, "Failure sending request") + return } result, err = client.ListResponder(resp) @@ -285,8 +307,9 @@ func (client RouteTablesClient) ListPreparer(resourceGroupName string) (*http.Re "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -344,13 +367,15 @@ func (client RouteTablesClient) ListNextResults(lastResults RouteTableListResult func (client RouteTablesClient) ListAll() (result RouteTableListResult, err error) { req, err := client.ListAllPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "ListAll", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "ListAll", nil, "Failure preparing request") + return } resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.RouteTablesClient", "ListAll", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.RouteTablesClient", "ListAll", resp, "Failure sending request") + return } result, err = client.ListAllResponder(resp) @@ -367,8 +392,9 @@ func (client RouteTablesClient) ListAllPreparer() (*http.Request, error) { "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( 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 old mode 100644 new mode 100755 index 37898c4d089c..3faaf007fffe --- 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,22 +14,17 @@ 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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" "net/http" ) -// SecurityGroupsClient 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 resources. The API has entities -// that capture the relationship between an end user and the Microsoft Azure -// Networks service. +// SecurityGroupsClient is the composite Swagger for Network Client type SecurityGroupsClient struct { ManagementClient } @@ -47,41 +42,45 @@ func NewSecurityGroupsClientWithBaseURI(baseURI string, subscriptionID string) S } // CreateOrUpdate creates or updates a network security group 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. +// 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 or update network security // group operation. -func (client SecurityGroupsClient) CreateOrUpdate(resourceGroupName string, networkSecurityGroupName string, parameters SecurityGroup, cancel <-chan struct{}) (result autorest.Response, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.SecurityGroupPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.SecurityGroupPropertiesFormat.NetworkInterfaces", Name: validation.ReadOnly, Rule: true, Chain: nil}, - {Target: "parameters.SecurityGroupPropertiesFormat.Subnets", Name: validation.ReadOnly, Rule: true, Chain: nil}, - }}}}}); err != nil { - return result, validation.NewErrorWithValidationError(err, "network.SecurityGroupsClient", "CreateOrUpdate") - } - - req, err := client.CreateOrUpdatePreparer(resourceGroupName, networkSecurityGroupName, parameters, cancel) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "CreateOrUpdate", nil, "Failure preparing request") - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "CreateOrUpdate", resp, "Failure sending request") - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "CreateOrUpdate", resp, "Failure responding to request") - } - - return +func (client SecurityGroupsClient) CreateOrUpdate(resourceGroupName string, networkSecurityGroupName string, parameters SecurityGroup, cancel <-chan struct{}) (<-chan SecurityGroup, <-chan error) { + resultChan := make(chan SecurityGroup, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result SecurityGroup + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.CreateOrUpdatePreparer(resourceGroupName, networkSecurityGroupName, parameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "CreateOrUpdate", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. @@ -92,8 +91,9 @@ func (client SecurityGroupsClient) CreateOrUpdatePreparer(resourceGroupName stri "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -116,13 +116,14 @@ func (client SecurityGroupsClient) CreateOrUpdateSender(req *http.Request) (*htt // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client SecurityGroupsClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { +func (client SecurityGroupsClient) CreateOrUpdateResponder(resp *http.Response) (result SecurityGroup, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } @@ -133,24 +134,37 @@ func (client SecurityGroupsClient) CreateOrUpdateResponder(resp *http.Response) // // 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, 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", nil, "Failure preparing request") - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Delete", resp, "Failure sending request") - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Delete", resp, "Failure responding to request") - } - - return +func (client SecurityGroupsClient) Delete(resourceGroupName string, networkSecurityGroupName string, cancel <-chan struct{}) (<-chan autorest.Response, <-chan error) { + resultChan := make(chan autorest.Response, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result autorest.Response + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeletePreparer(resourceGroupName, networkSecurityGroupName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Delete", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // DeletePreparer prepares the Delete request. @@ -161,8 +175,9 @@ func (client SecurityGroupsClient) DeletePreparer(resourceGroupName string, netw "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -201,13 +216,15 @@ func (client SecurityGroupsClient) DeleteResponder(resp *http.Response) (result 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Get", nil, "Failure preparing request") + return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Get", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "Get", resp, "Failure sending request") + return } result, err = client.GetResponder(resp) @@ -226,8 +243,9 @@ func (client SecurityGroupsClient) GetPreparer(resourceGroupName string, network "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } if len(expand) > 0 { queryParameters["$expand"] = autorest.Encode("query", expand) @@ -266,13 +284,15 @@ func (client SecurityGroupsClient) GetResponder(resp *http.Response) (result Sec 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "List", nil, "Failure preparing request") + return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "List", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "List", resp, "Failure sending request") + return } result, err = client.ListResponder(resp) @@ -290,8 +310,9 @@ func (client SecurityGroupsClient) ListPreparer(resourceGroupName string) (*http "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -349,13 +370,15 @@ func (client SecurityGroupsClient) ListNextResults(lastResults SecurityGroupList func (client SecurityGroupsClient) ListAll() (result SecurityGroupListResult, err error) { req, err := client.ListAllPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "ListAll", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "ListAll", nil, "Failure preparing request") + return } resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "ListAll", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.SecurityGroupsClient", "ListAll", resp, "Failure sending request") + return } result, err = client.ListAllResponder(resp) @@ -372,8 +395,9 @@ func (client SecurityGroupsClient) ListAllPreparer() (*http.Request, error) { "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( 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 old mode 100644 new mode 100755 index 9603c3c1fba2..2e2738605f83 --- 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,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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -25,11 +25,7 @@ import ( "net/http" ) -// SecurityRulesClient 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 resources. The API has entities -// that capture the relationship between an end user and the Microsoft Azure -// Networks service. +// SecurityRulesClient is the composite Swagger for Network Client type SecurityRulesClient struct { ManagementClient } @@ -47,42 +43,57 @@ func NewSecurityRulesClientWithBaseURI(baseURI string, subscriptionID string) Se } // CreateOrUpdate creates or updates a 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. +// 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 or update network security rule -// operation. -func (client SecurityRulesClient) CreateOrUpdate(resourceGroupName string, networkSecurityGroupName string, securityRuleName string, securityRuleParameters SecurityRule, cancel <-chan struct{}) (result autorest.Response, err error) { +// securityRuleName is the name of the security rule. securityRuleParameters is +// parameters supplied to the create or update network security rule operation. +func (client SecurityRulesClient) CreateOrUpdate(resourceGroupName string, networkSecurityGroupName string, securityRuleName string, securityRuleParameters SecurityRule, cancel <-chan struct{}) (<-chan SecurityRule, <-chan error) { + resultChan := make(chan SecurityRule, 1) + errChan := make(chan error, 1) if err := validation.Validate([]validation.Validation{ {TargetValue: securityRuleParameters, Constraints: []validation.Constraint{{Target: "securityRuleParameters.SecurityRulePropertiesFormat", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "securityRuleParameters.SecurityRulePropertiesFormat.SourceAddressPrefix", Name: validation.Null, Rule: true, Chain: nil}, {Target: "securityRuleParameters.SecurityRulePropertiesFormat.DestinationAddressPrefix", Name: validation.Null, Rule: true, Chain: nil}, }}}}}); err != nil { - return result, validation.NewErrorWithValidationError(err, "network.SecurityRulesClient", "CreateOrUpdate") + errChan <- validation.NewErrorWithValidationError(err, "network.SecurityRulesClient", "CreateOrUpdate") + close(errChan) + close(resultChan) + return resultChan, errChan } - req, err := client.CreateOrUpdatePreparer(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters, cancel) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.SecurityRulesClient", "CreateOrUpdate", nil, "Failure preparing request") - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.SecurityRulesClient", "CreateOrUpdate", resp, "Failure sending request") - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "CreateOrUpdate", resp, "Failure responding to request") - } - - return + go func() { + var err error + var result SecurityRule + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.CreateOrUpdatePreparer(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "CreateOrUpdate", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. @@ -94,8 +105,9 @@ func (client SecurityRulesClient) CreateOrUpdatePreparer(resourceGroupName strin "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -118,42 +130,56 @@ func (client SecurityRulesClient) CreateOrUpdateSender(req *http.Request) (*http // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client SecurityRulesClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { +func (client SecurityRulesClient) CreateOrUpdateResponder(resp *http.Response) (result SecurityRule, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } -// Delete deletes the specified 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. +// Delete deletes the specified 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, 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", nil, "Failure preparing request") - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.SecurityRulesClient", "Delete", resp, "Failure sending request") - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "Delete", resp, "Failure responding to request") - } - - return +func (client SecurityRulesClient) Delete(resourceGroupName string, networkSecurityGroupName string, securityRuleName string, cancel <-chan struct{}) (<-chan autorest.Response, <-chan error) { + resultChan := make(chan autorest.Response, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result autorest.Response + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeletePreparer(resourceGroupName, networkSecurityGroupName, securityRuleName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "Delete", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // DeletePreparer prepares the Delete request. @@ -165,8 +191,9 @@ func (client SecurityRulesClient) DeletePreparer(resourceGroupName string, netwo "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -205,13 +232,15 @@ func (client SecurityRulesClient) DeleteResponder(resp *http.Response) (result a 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "Get", nil, "Failure preparing request") + return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.SecurityRulesClient", "Get", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "Get", resp, "Failure sending request") + return } result, err = client.GetResponder(resp) @@ -231,8 +260,9 @@ func (client SecurityRulesClient) GetPreparer(resourceGroupName string, networkS "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -269,13 +299,15 @@ func (client SecurityRulesClient) GetResponder(resp *http.Response) (result Secu 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "List", nil, "Failure preparing request") + return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.SecurityRulesClient", "List", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.SecurityRulesClient", "List", resp, "Failure sending request") + return } result, err = client.ListResponder(resp) @@ -294,8 +326,9 @@ func (client SecurityRulesClient) ListPreparer(resourceGroupName string, network "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( 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 old mode 100644 new mode 100755 index 6230dbf03dc8..7d6ff882ae72 --- 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,22 +14,17 @@ 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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. import ( "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" "net/http" ) -// SubnetsClient 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 resources. The API has entities that -// capture the relationship between an end user and the Microsoft Azure -// Networks service. +// SubnetsClient is the composite Swagger for Network Client type SubnetsClient struct { ManagementClient } @@ -44,51 +39,46 @@ func NewSubnetsClientWithBaseURI(baseURI string, subscriptionID string) SubnetsC return SubnetsClient{NewWithBaseURI(baseURI, subscriptionID)} } -// CreateOrUpdate creates or updates a subnet in the specified 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. +// CreateOrUpdate creates or updates a subnet in the specified 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 or update subnet // operation. -func (client SubnetsClient) CreateOrUpdate(resourceGroupName string, virtualNetworkName string, subnetName string, subnetParameters Subnet, cancel <-chan struct{}) (result autorest.Response, err error) { - if err := validation.Validate([]validation.Validation{ - {TargetValue: subnetParameters, - Constraints: []validation.Constraint{{Target: "subnetParameters.SubnetPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "subnetParameters.SubnetPropertiesFormat.NetworkSecurityGroup", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "subnetParameters.SubnetPropertiesFormat.NetworkSecurityGroup.SecurityGroupPropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "subnetParameters.SubnetPropertiesFormat.NetworkSecurityGroup.SecurityGroupPropertiesFormat.NetworkInterfaces", Name: validation.ReadOnly, Rule: true, Chain: nil}, - {Target: "subnetParameters.SubnetPropertiesFormat.NetworkSecurityGroup.SecurityGroupPropertiesFormat.Subnets", Name: validation.ReadOnly, Rule: true, Chain: nil}, - }}, - }}, - {Target: "subnetParameters.SubnetPropertiesFormat.RouteTable", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "subnetParameters.SubnetPropertiesFormat.RouteTable.RouteTablePropertiesFormat", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "subnetParameters.SubnetPropertiesFormat.RouteTable.RouteTablePropertiesFormat.Subnets", Name: validation.ReadOnly, Rule: true, Chain: nil}}}, - }}, - {Target: "subnetParameters.SubnetPropertiesFormat.IPConfigurations", Name: validation.ReadOnly, Rule: true, Chain: nil}, - }}}}}); err != nil { - return result, validation.NewErrorWithValidationError(err, "network.SubnetsClient", "CreateOrUpdate") - } - - req, err := client.CreateOrUpdatePreparer(resourceGroupName, virtualNetworkName, subnetName, subnetParameters, cancel) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.SubnetsClient", "CreateOrUpdate", nil, "Failure preparing request") - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.SubnetsClient", "CreateOrUpdate", resp, "Failure sending request") - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubnetsClient", "CreateOrUpdate", resp, "Failure responding to request") - } - - return +func (client SubnetsClient) CreateOrUpdate(resourceGroupName string, virtualNetworkName string, subnetName string, subnetParameters Subnet, cancel <-chan struct{}) (<-chan Subnet, <-chan error) { + resultChan := make(chan Subnet, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result Subnet + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.CreateOrUpdatePreparer(resourceGroupName, virtualNetworkName, subnetName, subnetParameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.SubnetsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.SubnetsClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.SubnetsClient", "CreateOrUpdate", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. @@ -100,8 +90,9 @@ func (client SubnetsClient) CreateOrUpdatePreparer(resourceGroupName string, vir "virtualNetworkName": autorest.Encode("path", virtualNetworkName), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -124,40 +115,54 @@ func (client SubnetsClient) CreateOrUpdateSender(req *http.Request) (*http.Respo // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client SubnetsClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { +func (client SubnetsClient) CreateOrUpdateResponder(resp *http.Response) (result Subnet, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } // Delete 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. +// 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, 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", nil, "Failure preparing request") - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.SubnetsClient", "Delete", resp, "Failure sending request") - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.SubnetsClient", "Delete", resp, "Failure responding to request") - } - - return +func (client SubnetsClient) Delete(resourceGroupName string, virtualNetworkName string, subnetName string, cancel <-chan struct{}) (<-chan autorest.Response, <-chan error) { + resultChan := make(chan autorest.Response, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result autorest.Response + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeletePreparer(resourceGroupName, virtualNetworkName, subnetName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.SubnetsClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "network.SubnetsClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.SubnetsClient", "Delete", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // DeletePreparer prepares the Delete request. @@ -169,8 +174,9 @@ func (client SubnetsClient) DeletePreparer(resourceGroupName string, virtualNetw "virtualNetworkName": autorest.Encode("path", virtualNetworkName), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -209,13 +215,15 @@ func (client SubnetsClient) DeleteResponder(resp *http.Response) (result autores 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.SubnetsClient", "Get", nil, "Failure preparing request") + return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.SubnetsClient", "Get", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.SubnetsClient", "Get", resp, "Failure sending request") + return } result, err = client.GetResponder(resp) @@ -235,8 +243,9 @@ func (client SubnetsClient) GetPreparer(resourceGroupName string, virtualNetwork "virtualNetworkName": autorest.Encode("path", virtualNetworkName), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } if len(expand) > 0 { queryParameters["$expand"] = autorest.Encode("query", expand) @@ -276,13 +285,15 @@ func (client SubnetsClient) GetResponder(resp *http.Response) (result Subnet, er 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.SubnetsClient", "List", nil, "Failure preparing request") + return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.SubnetsClient", "List", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.SubnetsClient", "List", resp, "Failure sending request") + return } result, err = client.ListResponder(resp) @@ -301,8 +312,9 @@ func (client SubnetsClient) ListPreparer(resourceGroupName string, virtualNetwor "virtualNetworkName": autorest.Encode("path", virtualNetworkName), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( 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 old mode 100644 new mode 100755 index 016de70e1c30..34fa0df4b428 --- 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,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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -25,11 +25,7 @@ import ( "net/http" ) -// UsagesClient 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 resources. The API has entities that -// capture the relationship between an end user and the Microsoft Azure -// Networks service. +// UsagesClient is the composite Swagger for Network Client type UsagesClient struct { ManagementClient } @@ -56,13 +52,15 @@ func (client UsagesClient) List(location string) (result UsagesListResult, err e req, err := client.ListPreparer(location) if err != nil { - return result, autorest.NewErrorWithError(err, "network.UsagesClient", "List", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.UsagesClient", "List", nil, "Failure preparing request") + return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.UsagesClient", "List", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.UsagesClient", "List", resp, "Failure sending request") + return } result, err = client.ListResponder(resp) @@ -80,8 +78,9 @@ func (client UsagesClient) ListPreparer(location string) (*http.Request, error) "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( 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 old mode 100644 new mode 100755 index b0628fe0bd26..50b836179f85 --- 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,30 +14,16 @@ 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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. -import ( - "fmt" -) - -const ( - major = "7" - minor = "0" - 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 arm-%s/%s" -) - // UserAgent returns the UserAgent string to use when sending http.Requests. func UserAgent() string { - return fmt.Sprintf(userAgentFormat, Version(), "network", "2016-09-01") + return "Azure-SDK-For-Go/v10.0.2-beta arm-network/" } // Version returns the semantic version (see http://semver.org) of the client. func Version() string { - return fmt.Sprintf(semVerFormat, major, minor, patch, tag) + return "v10.0.2-beta" } 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 old mode 100644 new mode 100755 index d58a9d326fac..13e1392d2853 --- 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,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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -25,11 +25,8 @@ import ( "net/http" ) -// VirtualNetworkGatewayConnectionsClient 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 resources. The API -// has entities that capture the relationship between an end user and the -// Microsoft Azure Networks service. +// VirtualNetworkGatewayConnectionsClient is the composite Swagger for Network +// Client type VirtualNetworkGatewayConnectionsClient struct { ManagementClient } @@ -48,61 +45,60 @@ func NewVirtualNetworkGatewayConnectionsClientWithBaseURI(baseURI string, subscr // CreateOrUpdate creates or updates a virtual network gateway connection 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. +// 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. parameters is parameters supplied to the create or // update virtual network gateway connection operation. -func (client VirtualNetworkGatewayConnectionsClient) CreateOrUpdate(resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters VirtualNetworkGatewayConnection, cancel <-chan struct{}) (result autorest.Response, err error) { +func (client VirtualNetworkGatewayConnectionsClient) CreateOrUpdate(resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters VirtualNetworkGatewayConnection, cancel <-chan struct{}) (<-chan VirtualNetworkGatewayConnection, <-chan error) { + resultChan := make(chan VirtualNetworkGatewayConnection, 1) + errChan := make(chan error, 1) if err := validation.Validate([]validation.Validation{ {TargetValue: parameters, Constraints: []validation.Constraint{{Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat", Name: validation.Null, Rule: true, Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.VirtualNetworkGateway1", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.VirtualNetworkGateway1.VirtualNetworkGatewayPropertiesFormat", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.VirtualNetworkGateway1.VirtualNetworkGatewayPropertiesFormat.IPConfigurations", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.VirtualNetworkGateway1.VirtualNetworkGatewayPropertiesFormat.ProvisioningState", Name: validation.ReadOnly, Rule: true, Chain: nil}, - }}, - }}, + Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.VirtualNetworkGateway1.VirtualNetworkGatewayPropertiesFormat", Name: validation.Null, Rule: true, Chain: nil}}}, {Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.VirtualNetworkGateway2", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.VirtualNetworkGateway2.VirtualNetworkGatewayPropertiesFormat", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.VirtualNetworkGateway2.VirtualNetworkGatewayPropertiesFormat.IPConfigurations", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.VirtualNetworkGateway2.VirtualNetworkGatewayPropertiesFormat.ProvisioningState", Name: validation.ReadOnly, Rule: true, Chain: nil}, - }}, - }}, + Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.VirtualNetworkGateway2.VirtualNetworkGatewayPropertiesFormat", Name: validation.Null, Rule: true, Chain: nil}}}, {Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.LocalNetworkGateway2", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.LocalNetworkGateway2.LocalNetworkGatewayPropertiesFormat", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.LocalNetworkGateway2.LocalNetworkGatewayPropertiesFormat.LocalNetworkAddressSpace", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.LocalNetworkGateway2.LocalNetworkGatewayPropertiesFormat.ProvisioningState", Name: validation.ReadOnly, Rule: true, Chain: nil}, - }}, - }}, - {Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.ConnectionStatus", Name: validation.ReadOnly, Rule: true, Chain: nil}, - {Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.TunnelConnectionStatus", Name: validation.ReadOnly, Rule: true, Chain: nil}, - {Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.EgressBytesTransferred", Name: validation.ReadOnly, Rule: true, Chain: nil}, - {Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.IngressBytesTransferred", Name: validation.ReadOnly, Rule: true, Chain: nil}, - {Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.ProvisioningState", Name: validation.ReadOnly, Rule: true, Chain: nil}, + Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkGatewayConnectionPropertiesFormat.LocalNetworkGateway2.LocalNetworkGatewayPropertiesFormat", Name: validation.Null, Rule: true, Chain: nil}}}, }}}}}); err != nil { - return result, validation.NewErrorWithValidationError(err, "network.VirtualNetworkGatewayConnectionsClient", "CreateOrUpdate") - } - - req, err := client.CreateOrUpdatePreparer(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, cancel) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "CreateOrUpdate", nil, "Failure preparing request") - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "CreateOrUpdate", resp, "Failure sending request") - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "CreateOrUpdate", resp, "Failure responding to request") - } - - return + errChan <- validation.NewErrorWithValidationError(err, "network.VirtualNetworkGatewayConnectionsClient", "CreateOrUpdate") + close(errChan) + close(resultChan) + return resultChan, errChan + } + + go func() { + var err error + var result VirtualNetworkGatewayConnection + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.CreateOrUpdatePreparer(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "CreateOrUpdate", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. @@ -113,8 +109,9 @@ func (client VirtualNetworkGatewayConnectionsClient) CreateOrUpdatePreparer(reso "virtualNetworkGatewayConnectionName": autorest.Encode("path", virtualNetworkGatewayConnectionName), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -137,42 +134,56 @@ func (client VirtualNetworkGatewayConnectionsClient) CreateOrUpdateSender(req *h // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client VirtualNetworkGatewayConnectionsClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualNetworkGatewayConnectionsClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualNetworkGatewayConnection, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } -// Delete deletes the specified virtual network Gateway connection. 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. +// Delete deletes the specified virtual network Gateway connection. 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, 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", nil, "Failure preparing request") - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "Delete", resp, "Failure sending request") - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "Delete", resp, "Failure responding to request") - } - - return +func (client VirtualNetworkGatewayConnectionsClient) Delete(resourceGroupName string, virtualNetworkGatewayConnectionName string, cancel <-chan struct{}) (<-chan autorest.Response, <-chan error) { + resultChan := make(chan autorest.Response, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result autorest.Response + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeletePreparer(resourceGroupName, virtualNetworkGatewayConnectionName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "Delete", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // DeletePreparer prepares the Delete request. @@ -183,8 +194,9 @@ func (client VirtualNetworkGatewayConnectionsClient) DeletePreparer(resourceGrou "virtualNetworkGatewayConnectionName": autorest.Encode("path", virtualNetworkGatewayConnectionName), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -223,13 +235,15 @@ func (client VirtualNetworkGatewayConnectionsClient) DeleteResponder(resp *http. 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "Get", nil, "Failure preparing request") + return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "Get", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "Get", resp, "Failure sending request") + return } result, err = client.GetResponder(resp) @@ -248,8 +262,9 @@ func (client VirtualNetworkGatewayConnectionsClient) GetPreparer(resourceGroupNa "virtualNetworkGatewayConnectionName": autorest.Encode("path", virtualNetworkGatewayConnectionName), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -280,8 +295,8 @@ func (client VirtualNetworkGatewayConnectionsClient) GetResponder(resp *http.Res } // GetSharedKey the Get VirtualNetworkGatewayConnectionSharedKey operation -// retrieves information about the specified virtual network gateway -// connection shared key through Network resource provider. +// retrieves information about the specified virtual network gateway connection +// shared key through Network resource provider. // // resourceGroupName is the name of the resource group. // virtualNetworkGatewayConnectionName is the virtual network gateway @@ -289,13 +304,15 @@ func (client VirtualNetworkGatewayConnectionsClient) GetResponder(resp *http.Res func (client VirtualNetworkGatewayConnectionsClient) GetSharedKey(resourceGroupName string, virtualNetworkGatewayConnectionName string) (result ConnectionSharedKey, err error) { req, err := client.GetSharedKeyPreparer(resourceGroupName, virtualNetworkGatewayConnectionName) if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "GetSharedKey", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "GetSharedKey", nil, "Failure preparing request") + return } resp, err := client.GetSharedKeySender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "GetSharedKey", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "GetSharedKey", resp, "Failure sending request") + return } result, err = client.GetSharedKeyResponder(resp) @@ -314,8 +331,9 @@ func (client VirtualNetworkGatewayConnectionsClient) GetSharedKeyPreparer(resour "virtualNetworkGatewayConnectionName": autorest.Encode("path", virtualNetworkGatewayConnectionName), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -352,13 +370,15 @@ func (client VirtualNetworkGatewayConnectionsClient) GetSharedKeyResponder(resp 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "List", nil, "Failure preparing request") + return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "List", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "List", resp, "Failure sending request") + return } result, err = client.ListResponder(resp) @@ -376,8 +396,9 @@ func (client VirtualNetworkGatewayConnectionsClient) ListPreparer(resourceGroupN "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -432,44 +453,60 @@ 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. 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. +// resets the virtual network gateway connection shared key for passed virtual +// network gateway connection in 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. // 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, cancel <-chan struct{}) (result autorest.Response, err error) { +// begin reset virtual network gateway connection shared key operation through +// network resource provider. +func (client VirtualNetworkGatewayConnectionsClient) ResetSharedKey(resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters ConnectionResetSharedKey, cancel <-chan struct{}) (<-chan ConnectionResetSharedKey, <-chan error) { + resultChan := make(chan ConnectionResetSharedKey, 1) + errChan := make(chan error, 1) if err := validation.Validate([]validation.Validation{ {TargetValue: parameters, Constraints: []validation.Constraint{{Target: "parameters.KeyLength", Name: validation.Null, Rule: true, Chain: []validation.Constraint{{Target: "parameters.KeyLength", Name: validation.InclusiveMaximum, Rule: 128, Chain: nil}, {Target: "parameters.KeyLength", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil}, }}}}}); err != nil { - return result, validation.NewErrorWithValidationError(err, "network.VirtualNetworkGatewayConnectionsClient", "ResetSharedKey") - } - - req, err := client.ResetSharedKeyPreparer(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, cancel) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "ResetSharedKey", nil, "Failure preparing request") - } - - resp, err := client.ResetSharedKeySender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "ResetSharedKey", resp, "Failure sending request") - } - - result, err = client.ResetSharedKeyResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "ResetSharedKey", resp, "Failure responding to request") - } - - return + errChan <- validation.NewErrorWithValidationError(err, "network.VirtualNetworkGatewayConnectionsClient", "ResetSharedKey") + close(errChan) + close(resultChan) + return resultChan, errChan + } + + go func() { + var err error + var result ConnectionResetSharedKey + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.ResetSharedKeyPreparer(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "ResetSharedKey", nil, "Failure preparing request") + return + } + + resp, err := client.ResetSharedKeySender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "ResetSharedKey", resp, "Failure sending request") + return + } + + result, err = client.ResetSharedKeyResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "ResetSharedKey", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // ResetSharedKeyPreparer prepares the ResetSharedKey request. @@ -480,8 +517,9 @@ func (client VirtualNetworkGatewayConnectionsClient) ResetSharedKeyPreparer(reso "virtualNetworkGatewayConnectionName": autorest.Encode("path", virtualNetworkGatewayConnectionName), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -504,52 +542,69 @@ func (client VirtualNetworkGatewayConnectionsClient) ResetSharedKeySender(req *h // ResetSharedKeyResponder handles the response to the ResetSharedKey request. The method always // closes the http.Response Body. -func (client VirtualNetworkGatewayConnectionsClient) ResetSharedKeyResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualNetworkGatewayConnectionsClient) ResetSharedKeyResponder(resp *http.Response) (result ConnectionResetSharedKey, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{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. 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. +// 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. 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 connection Shared key operation throughNetwork -// resource provider. -func (client VirtualNetworkGatewayConnectionsClient) SetSharedKey(resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters ConnectionSharedKey, cancel <-chan struct{}) (result autorest.Response, err error) { +// connection name. parameters is parameters supplied to the Begin Set Virtual +// Network Gateway connection Shared key operation throughNetwork resource +// provider. +func (client VirtualNetworkGatewayConnectionsClient) SetSharedKey(resourceGroupName string, virtualNetworkGatewayConnectionName string, parameters ConnectionSharedKey, cancel <-chan struct{}) (<-chan ConnectionSharedKey, <-chan error) { + resultChan := make(chan ConnectionSharedKey, 1) + errChan := make(chan error, 1) if err := validation.Validate([]validation.Validation{ {TargetValue: parameters, Constraints: []validation.Constraint{{Target: "parameters.Value", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewErrorWithValidationError(err, "network.VirtualNetworkGatewayConnectionsClient", "SetSharedKey") - } - - req, err := client.SetSharedKeyPreparer(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, cancel) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "SetSharedKey", nil, "Failure preparing request") - } - - resp, err := client.SetSharedKeySender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "SetSharedKey", resp, "Failure sending request") - } - - result, err = client.SetSharedKeyResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "SetSharedKey", resp, "Failure responding to request") - } - - return + errChan <- validation.NewErrorWithValidationError(err, "network.VirtualNetworkGatewayConnectionsClient", "SetSharedKey") + close(errChan) + close(resultChan) + return resultChan, errChan + } + + go func() { + var err error + var result ConnectionSharedKey + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.SetSharedKeyPreparer(resourceGroupName, virtualNetworkGatewayConnectionName, parameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "SetSharedKey", nil, "Failure preparing request") + return + } + + resp, err := client.SetSharedKeySender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "SetSharedKey", resp, "Failure sending request") + return + } + + result, err = client.SetSharedKeyResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewayConnectionsClient", "SetSharedKey", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // SetSharedKeyPreparer prepares the SetSharedKey request. @@ -560,8 +615,9 @@ func (client VirtualNetworkGatewayConnectionsClient) SetSharedKeyPreparer(resour "virtualNetworkGatewayConnectionName": autorest.Encode("path", virtualNetworkGatewayConnectionName), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -584,12 +640,13 @@ func (client VirtualNetworkGatewayConnectionsClient) SetSharedKeySender(req *htt // SetSharedKeyResponder handles the response to the SetSharedKey request. The method always // closes the http.Response Body. -func (client VirtualNetworkGatewayConnectionsClient) SetSharedKeyResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualNetworkGatewayConnectionsClient) SetSharedKeyResponder(resp *http.Response) (result ConnectionSharedKey, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{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 old mode 100644 new mode 100755 index 2a6ce4772dfb..720978e83ff8 --- 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,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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -25,11 +25,7 @@ import ( "net/http" ) -// VirtualNetworkGatewaysClient 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 resources. The API has -// entities that capture the relationship between an end user and the -// Microsoft Azure Networks service. +// VirtualNetworkGatewaysClient is the composite Swagger for Network Client type VirtualNetworkGatewaysClient struct { ManagementClient } @@ -46,42 +42,55 @@ func NewVirtualNetworkGatewaysClientWithBaseURI(baseURI string, subscriptionID s return VirtualNetworkGatewaysClient{NewWithBaseURI(baseURI, subscriptionID)} } -// CreateOrUpdate creates or updates a virtual network gateway 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. +// CreateOrUpdate creates or updates a virtual network gateway 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. // virtualNetworkGatewayName is the name of the virtual network gateway. // parameters is parameters supplied to create or update virtual network // gateway operation. -func (client VirtualNetworkGatewaysClient) CreateOrUpdate(resourceGroupName string, virtualNetworkGatewayName string, parameters VirtualNetworkGateway, cancel <-chan struct{}) (result autorest.Response, err error) { +func (client VirtualNetworkGatewaysClient) CreateOrUpdate(resourceGroupName string, virtualNetworkGatewayName string, parameters VirtualNetworkGateway, cancel <-chan struct{}) (<-chan VirtualNetworkGateway, <-chan error) { + resultChan := make(chan VirtualNetworkGateway, 1) + errChan := make(chan error, 1) if err := validation.Validate([]validation.Validation{ {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.VirtualNetworkGatewayPropertiesFormat", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "parameters.VirtualNetworkGatewayPropertiesFormat.IPConfigurations", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.VirtualNetworkGatewayPropertiesFormat.ProvisioningState", Name: validation.ReadOnly, Rule: true, Chain: nil}, - }}}}}); err != nil { - return result, validation.NewErrorWithValidationError(err, "network.VirtualNetworkGatewaysClient", "CreateOrUpdate") - } - - req, err := client.CreateOrUpdatePreparer(resourceGroupName, virtualNetworkGatewayName, parameters, cancel) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "CreateOrUpdate", nil, "Failure preparing request") - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "CreateOrUpdate", resp, "Failure sending request") - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "CreateOrUpdate", resp, "Failure responding to request") - } - - return + Constraints: []validation.Constraint{{Target: "parameters.VirtualNetworkGatewayPropertiesFormat", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + errChan <- validation.NewErrorWithValidationError(err, "network.VirtualNetworkGatewaysClient", "CreateOrUpdate") + close(errChan) + close(resultChan) + return resultChan, errChan + } + + go func() { + var err error + var result VirtualNetworkGateway + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.CreateOrUpdatePreparer(resourceGroupName, virtualNetworkGatewayName, parameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "CreateOrUpdate", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. @@ -92,8 +101,9 @@ func (client VirtualNetworkGatewaysClient) CreateOrUpdatePreparer(resourceGroupN "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -116,13 +126,14 @@ func (client VirtualNetworkGatewaysClient) CreateOrUpdateSender(req *http.Reques // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualNetworkGatewaysClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualNetworkGateway, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } @@ -133,24 +144,37 @@ func (client VirtualNetworkGatewaysClient) CreateOrUpdateResponder(resp *http.Re // // 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, 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", nil, "Failure preparing request") - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Delete", resp, "Failure sending request") - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Delete", resp, "Failure responding to request") - } - - return +func (client VirtualNetworkGatewaysClient) Delete(resourceGroupName string, virtualNetworkGatewayName string, cancel <-chan struct{}) (<-chan autorest.Response, <-chan error) { + resultChan := make(chan autorest.Response, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result autorest.Response + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeletePreparer(resourceGroupName, virtualNetworkGatewayName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Delete", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // DeletePreparer prepares the Delete request. @@ -161,8 +185,9 @@ func (client VirtualNetworkGatewaysClient) DeletePreparer(resourceGroupName stri "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -203,13 +228,15 @@ func (client VirtualNetworkGatewaysClient) DeleteResponder(resp *http.Response) 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Generatevpnclientpackage", nil, "Failure preparing request") + return } resp, err := client.GeneratevpnclientpackageSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Generatevpnclientpackage", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Generatevpnclientpackage", resp, "Failure sending request") + return } result, err = client.GeneratevpnclientpackageResponder(resp) @@ -228,8 +255,9 @@ func (client VirtualNetworkGatewaysClient) GeneratevpnclientpackagePreparer(reso "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -268,13 +296,15 @@ func (client VirtualNetworkGatewaysClient) GeneratevpnclientpackageResponder(res 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Get", nil, "Failure preparing request") + return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Get", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Get", resp, "Failure sending request") + return } result, err = client.GetResponder(resp) @@ -293,8 +323,9 @@ func (client VirtualNetworkGatewaysClient) GetPreparer(resourceGroupName string, "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -324,19 +355,275 @@ func (client VirtualNetworkGatewaysClient) GetResponder(resp *http.Response) (re return } +// GetAdvertisedRoutes this operation retrieves a list of routes the virtual +// network gateway is advertising to the specified peer. 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. peer +// is the IP address of the peer +func (client VirtualNetworkGatewaysClient) GetAdvertisedRoutes(resourceGroupName string, virtualNetworkGatewayName string, peer string, cancel <-chan struct{}) (<-chan GatewayRouteListResult, <-chan error) { + resultChan := make(chan GatewayRouteListResult, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result GatewayRouteListResult + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.GetAdvertisedRoutesPreparer(resourceGroupName, virtualNetworkGatewayName, peer, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GetAdvertisedRoutes", nil, "Failure preparing request") + return + } + + resp, err := client.GetAdvertisedRoutesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GetAdvertisedRoutes", resp, "Failure sending request") + return + } + + result, err = client.GetAdvertisedRoutesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GetAdvertisedRoutes", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// GetAdvertisedRoutesPreparer prepares the GetAdvertisedRoutes request. +func (client VirtualNetworkGatewaysClient) GetAdvertisedRoutesPreparer(resourceGroupName string, virtualNetworkGatewayName string, peer string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + "peer": autorest.Encode("query", peer), + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/getAdvertisedRoutes", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// GetAdvertisedRoutesSender sends the GetAdvertisedRoutes request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualNetworkGatewaysClient) GetAdvertisedRoutesSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// GetAdvertisedRoutesResponder handles the response to the GetAdvertisedRoutes request. The method always +// closes the http.Response Body. +func (client VirtualNetworkGatewaysClient) GetAdvertisedRoutesResponder(resp *http.Response) (result GatewayRouteListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetBgpPeerStatus the GetBgpPeerStatus operation retrieves the status of all +// BGP peers. 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. peer +// is the IP address of the peer to retrieve the status of. +func (client VirtualNetworkGatewaysClient) GetBgpPeerStatus(resourceGroupName string, virtualNetworkGatewayName string, peer string, cancel <-chan struct{}) (<-chan BgpPeerStatusListResult, <-chan error) { + resultChan := make(chan BgpPeerStatusListResult, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result BgpPeerStatusListResult + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.GetBgpPeerStatusPreparer(resourceGroupName, virtualNetworkGatewayName, peer, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GetBgpPeerStatus", nil, "Failure preparing request") + return + } + + resp, err := client.GetBgpPeerStatusSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GetBgpPeerStatus", resp, "Failure sending request") + return + } + + result, err = client.GetBgpPeerStatusResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GetBgpPeerStatus", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// GetBgpPeerStatusPreparer prepares the GetBgpPeerStatus request. +func (client VirtualNetworkGatewaysClient) GetBgpPeerStatusPreparer(resourceGroupName string, virtualNetworkGatewayName string, peer string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if len(peer) > 0 { + queryParameters["peer"] = autorest.Encode("query", peer) + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/getBgpPeerStatus", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// GetBgpPeerStatusSender sends the GetBgpPeerStatus request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualNetworkGatewaysClient) GetBgpPeerStatusSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// GetBgpPeerStatusResponder handles the response to the GetBgpPeerStatus request. The method always +// closes the http.Response Body. +func (client VirtualNetworkGatewaysClient) GetBgpPeerStatusResponder(resp *http.Response) (result BgpPeerStatusListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetLearnedRoutes this operation retrieves a list of routes the virtual +// network gateway has learned, including routes learned from BGP peers. 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) GetLearnedRoutes(resourceGroupName string, virtualNetworkGatewayName string, cancel <-chan struct{}) (<-chan GatewayRouteListResult, <-chan error) { + resultChan := make(chan GatewayRouteListResult, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result GatewayRouteListResult + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.GetLearnedRoutesPreparer(resourceGroupName, virtualNetworkGatewayName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GetLearnedRoutes", nil, "Failure preparing request") + return + } + + resp, err := client.GetLearnedRoutesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GetLearnedRoutes", resp, "Failure sending request") + return + } + + result, err = client.GetLearnedRoutesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "GetLearnedRoutes", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// GetLearnedRoutesPreparer prepares the GetLearnedRoutes request. +func (client VirtualNetworkGatewaysClient) GetLearnedRoutesPreparer(resourceGroupName string, virtualNetworkGatewayName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/getLearnedRoutes", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// GetLearnedRoutesSender sends the GetLearnedRoutes request. The method will close the +// http.Response Body if it receives an error. +func (client VirtualNetworkGatewaysClient) GetLearnedRoutesSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// GetLearnedRoutesResponder handles the response to the GetLearnedRoutes request. The method always +// closes the http.Response Body. +func (client VirtualNetworkGatewaysClient) GetLearnedRoutesResponder(resp *http.Response) (result GatewayRouteListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + // List gets all virtual network gateways by resource group. // // resourceGroupName is the name of the resource group. 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "List", nil, "Failure preparing request") + return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "List", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "List", resp, "Failure sending request") + return } result, err = client.ListResponder(resp) @@ -354,8 +641,9 @@ func (client VirtualNetworkGatewaysClient) ListPreparer(resourceGroupName string "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -410,32 +698,45 @@ func (client VirtualNetworkGatewaysClient) ListNextResults(lastResults VirtualNe } // Reset resets the primary of the virtual network gateway 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. +// 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. // virtualNetworkGatewayName is the name of the virtual network gateway. // gatewayVip is virtual network gateway vip address supplied to the begin // reset of the active-active feature enabled gateway. -func (client VirtualNetworkGatewaysClient) Reset(resourceGroupName string, virtualNetworkGatewayName string, gatewayVip string, cancel <-chan struct{}) (result autorest.Response, err error) { - req, err := client.ResetPreparer(resourceGroupName, virtualNetworkGatewayName, gatewayVip, cancel) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Reset", nil, "Failure preparing request") - } - - resp, err := client.ResetSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Reset", resp, "Failure sending request") - } - - result, err = client.ResetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Reset", resp, "Failure responding to request") - } - - return +func (client VirtualNetworkGatewaysClient) Reset(resourceGroupName string, virtualNetworkGatewayName string, gatewayVip string, cancel <-chan struct{}) (<-chan VirtualNetworkGateway, <-chan error) { + resultChan := make(chan VirtualNetworkGateway, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result VirtualNetworkGateway + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.ResetPreparer(resourceGroupName, virtualNetworkGatewayName, gatewayVip, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Reset", nil, "Failure preparing request") + return + } + + resp, err := client.ResetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Reset", resp, "Failure sending request") + return + } + + result, err = client.ResetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkGatewaysClient", "Reset", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // ResetPreparer prepares the Reset request. @@ -446,8 +747,9 @@ func (client VirtualNetworkGatewaysClient) ResetPreparer(resourceGroupName strin "virtualNetworkGatewayName": autorest.Encode("path", virtualNetworkGatewayName), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } if len(gatewayVip) > 0 { queryParameters["gatewayVip"] = autorest.Encode("query", gatewayVip) @@ -471,12 +773,13 @@ func (client VirtualNetworkGatewaysClient) ResetSender(req *http.Request) (*http // ResetResponder handles the response to the Reset request. The method always // closes the http.Response Body. -func (client VirtualNetworkGatewaysClient) ResetResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualNetworkGatewaysClient) ResetResponder(resp *http.Response) (result VirtualNetworkGateway, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusOK), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/virtualnetworkpeerings.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/virtualnetworkpeerings.go old mode 100644 new mode 100755 index bfed897a3bf9..27fafdfd0a46 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/virtualnetworkpeerings.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/virtualnetworkpeerings.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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -24,11 +24,7 @@ import ( "net/http" ) -// VirtualNetworkPeeringsClient 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 resources. The API has -// entities that capture the relationship between an end user and the -// Microsoft Azure Networks service. +// VirtualNetworkPeeringsClient is the composite Swagger for Network Client type VirtualNetworkPeeringsClient struct { ManagementClient } @@ -54,24 +50,37 @@ func NewVirtualNetworkPeeringsClientWithBaseURI(baseURI string, subscriptionID s // the name of the virtual network. virtualNetworkPeeringName is the name of // the peering. virtualNetworkPeeringParameters is parameters supplied to the // create or update virtual network peering operation. -func (client VirtualNetworkPeeringsClient) CreateOrUpdate(resourceGroupName string, virtualNetworkName string, virtualNetworkPeeringName string, virtualNetworkPeeringParameters VirtualNetworkPeering, cancel <-chan struct{}) (result autorest.Response, err error) { - req, err := client.CreateOrUpdatePreparer(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, virtualNetworkPeeringParameters, cancel) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "CreateOrUpdate", nil, "Failure preparing request") - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "CreateOrUpdate", resp, "Failure sending request") - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "CreateOrUpdate", resp, "Failure responding to request") - } - - return +func (client VirtualNetworkPeeringsClient) CreateOrUpdate(resourceGroupName string, virtualNetworkName string, virtualNetworkPeeringName string, virtualNetworkPeeringParameters VirtualNetworkPeering, cancel <-chan struct{}) (<-chan VirtualNetworkPeering, <-chan error) { + resultChan := make(chan VirtualNetworkPeering, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result VirtualNetworkPeering + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.CreateOrUpdatePreparer(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, virtualNetworkPeeringParameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "CreateOrUpdate", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. @@ -83,8 +92,9 @@ func (client VirtualNetworkPeeringsClient) CreateOrUpdatePreparer(resourceGroupN "virtualNetworkPeeringName": autorest.Encode("path", virtualNetworkPeeringName), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -107,13 +117,14 @@ func (client VirtualNetworkPeeringsClient) CreateOrUpdateSender(req *http.Reques // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client VirtualNetworkPeeringsClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualNetworkPeeringsClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualNetworkPeering, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } @@ -125,24 +136,37 @@ func (client VirtualNetworkPeeringsClient) CreateOrUpdateResponder(resp *http.Re // resourceGroupName is the name of the resource group. virtualNetworkName is // the name of the virtual network. virtualNetworkPeeringName is the name of // the virtual network peering. -func (client VirtualNetworkPeeringsClient) Delete(resourceGroupName string, virtualNetworkName string, virtualNetworkPeeringName string, cancel <-chan struct{}) (result autorest.Response, err error) { - req, err := client.DeletePreparer(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, cancel) - if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "Delete", nil, "Failure preparing request") - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "Delete", resp, "Failure sending request") - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "Delete", resp, "Failure responding to request") - } - - return +func (client VirtualNetworkPeeringsClient) Delete(resourceGroupName string, virtualNetworkName string, virtualNetworkPeeringName string, cancel <-chan struct{}) (<-chan autorest.Response, <-chan error) { + resultChan := make(chan autorest.Response, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result autorest.Response + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeletePreparer(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "Delete", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // DeletePreparer prepares the Delete request. @@ -154,8 +178,9 @@ func (client VirtualNetworkPeeringsClient) DeletePreparer(resourceGroupName stri "virtualNetworkPeeringName": autorest.Encode("path", virtualNetworkPeeringName), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -194,13 +219,15 @@ func (client VirtualNetworkPeeringsClient) DeleteResponder(resp *http.Response) func (client VirtualNetworkPeeringsClient) Get(resourceGroupName string, virtualNetworkName string, virtualNetworkPeeringName string) (result VirtualNetworkPeering, err error) { req, err := client.GetPreparer(resourceGroupName, virtualNetworkName, virtualNetworkPeeringName) if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "Get", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "Get", nil, "Failure preparing request") + return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "Get", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "Get", resp, "Failure sending request") + return } result, err = client.GetResponder(resp) @@ -220,8 +247,9 @@ func (client VirtualNetworkPeeringsClient) GetPreparer(resourceGroupName string, "virtualNetworkPeeringName": autorest.Encode("path", virtualNetworkPeeringName), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -258,13 +286,15 @@ func (client VirtualNetworkPeeringsClient) GetResponder(resp *http.Response) (re func (client VirtualNetworkPeeringsClient) List(resourceGroupName string, virtualNetworkName string) (result VirtualNetworkPeeringListResult, err error) { req, err := client.ListPreparer(resourceGroupName, virtualNetworkName) if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "List", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "List", nil, "Failure preparing request") + return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "List", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworkPeeringsClient", "List", resp, "Failure sending request") + return } result, err = client.ListResponder(resp) @@ -283,8 +313,9 @@ func (client VirtualNetworkPeeringsClient) ListPreparer(resourceGroupName string "virtualNetworkName": autorest.Encode("path", virtualNetworkName), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( 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 old mode 100644 new mode 100755 index 9046437af2df..eab048c7252e --- 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,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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -24,11 +24,7 @@ import ( "net/http" ) -// VirtualNetworksClient 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 resources. The API has entities -// that capture the relationship between an end user and the Microsoft Azure -// Networks service. +// VirtualNetworksClient is the composite Swagger for Network Client type VirtualNetworksClient struct { ManagementClient } @@ -49,18 +45,20 @@ func NewVirtualNetworksClientWithBaseURI(baseURI string, subscriptionID string) // for use. // // resourceGroupName is the name of the resource group. virtualNetworkName is -// the name of the virtual network. ipAddress is the private IP address to be +// the name of the virtual network. IPAddress is the private IP address to be // verified. -func (client VirtualNetworksClient) CheckIPAddressAvailability(resourceGroupName string, virtualNetworkName string, ipAddress string) (result IPAddressAvailabilityResult, err error) { - req, err := client.CheckIPAddressAvailabilityPreparer(resourceGroupName, virtualNetworkName, ipAddress) +func (client VirtualNetworksClient) CheckIPAddressAvailability(resourceGroupName string, virtualNetworkName string, IPAddress string) (result IPAddressAvailabilityResult, err error) { + req, err := client.CheckIPAddressAvailabilityPreparer(resourceGroupName, virtualNetworkName, IPAddress) if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "CheckIPAddressAvailability", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "CheckIPAddressAvailability", nil, "Failure preparing request") + return } resp, err := client.CheckIPAddressAvailabilitySender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "CheckIPAddressAvailability", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "CheckIPAddressAvailability", resp, "Failure sending request") + return } result, err = client.CheckIPAddressAvailabilityResponder(resp) @@ -72,18 +70,19 @@ func (client VirtualNetworksClient) CheckIPAddressAvailability(resourceGroupName } // CheckIPAddressAvailabilityPreparer prepares the CheckIPAddressAvailability request. -func (client VirtualNetworksClient) CheckIPAddressAvailabilityPreparer(resourceGroupName string, virtualNetworkName string, ipAddress string) (*http.Request, error) { +func (client VirtualNetworksClient) CheckIPAddressAvailabilityPreparer(resourceGroupName string, virtualNetworkName string, IPAddress string) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "virtualNetworkName": autorest.Encode("path", virtualNetworkName), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } - if len(ipAddress) > 0 { - queryParameters["ipAddress"] = autorest.Encode("query", ipAddress) + if len(IPAddress) > 0 { + queryParameters["ipAddress"] = autorest.Encode("query", IPAddress) } preparer := autorest.CreatePreparer( @@ -114,31 +113,44 @@ func (client VirtualNetworksClient) CheckIPAddressAvailabilityResponder(resp *ht } // CreateOrUpdate creates or updates a virtual 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. +// 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 or update virtual network operation -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", nil, "Failure preparing request") - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "CreateOrUpdate", resp, "Failure sending request") - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "CreateOrUpdate", resp, "Failure responding to request") - } - - return +func (client VirtualNetworksClient) CreateOrUpdate(resourceGroupName string, virtualNetworkName string, parameters VirtualNetwork, cancel <-chan struct{}) (<-chan VirtualNetwork, <-chan error) { + resultChan := make(chan VirtualNetwork, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result VirtualNetwork + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.CreateOrUpdatePreparer(resourceGroupName, virtualNetworkName, parameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "CreateOrUpdate", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. @@ -149,8 +161,9 @@ func (client VirtualNetworksClient) CreateOrUpdatePreparer(resourceGroupName str "virtualNetworkName": autorest.Encode("path", virtualNetworkName), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -173,41 +186,55 @@ func (client VirtualNetworksClient) CreateOrUpdateSender(req *http.Request) (*ht // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. -func (client VirtualNetworksClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) { +func (client VirtualNetworksClient) CreateOrUpdateResponder(resp *http.Response) (result VirtualNetwork, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } // Delete deletes the specified 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. +// 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, 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", nil, "Failure preparing request") - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "Delete", resp, "Failure sending request") - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "Delete", resp, "Failure responding to request") - } - - return +func (client VirtualNetworksClient) Delete(resourceGroupName string, virtualNetworkName string, cancel <-chan struct{}) (<-chan autorest.Response, <-chan error) { + resultChan := make(chan autorest.Response, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result autorest.Response + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeletePreparer(resourceGroupName, virtualNetworkName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "Delete", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // DeletePreparer prepares the Delete request. @@ -218,8 +245,9 @@ func (client VirtualNetworksClient) DeletePreparer(resourceGroupName string, vir "virtualNetworkName": autorest.Encode("path", virtualNetworkName), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -257,13 +285,15 @@ func (client VirtualNetworksClient) DeleteResponder(resp *http.Response) (result 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "Get", nil, "Failure preparing request") + return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "Get", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "Get", resp, "Failure sending request") + return } result, err = client.GetResponder(resp) @@ -282,8 +312,9 @@ func (client VirtualNetworksClient) GetPreparer(resourceGroupName string, virtua "virtualNetworkName": autorest.Encode("path", virtualNetworkName), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } if len(expand) > 0 { queryParameters["$expand"] = autorest.Encode("query", expand) @@ -322,13 +353,15 @@ func (client VirtualNetworksClient) GetResponder(resp *http.Response) (result Vi 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", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "List", nil, "Failure preparing request") + return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "List", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "List", resp, "Failure sending request") + return } result, err = client.ListResponder(resp) @@ -346,8 +379,9 @@ func (client VirtualNetworksClient) ListPreparer(resourceGroupName string) (*htt "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -405,13 +439,15 @@ func (client VirtualNetworksClient) ListNextResults(lastResults VirtualNetworkLi func (client VirtualNetworksClient) ListAll() (result VirtualNetworkListResult, err error) { req, err := client.ListAllPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "ListAll", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "ListAll", nil, "Failure preparing request") + return } resp, err := client.ListAllSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "ListAll", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "network.VirtualNetworksClient", "ListAll", resp, "Failure sending request") + return } result, err = client.ListAllResponder(resp) @@ -428,8 +464,9 @@ func (client VirtualNetworksClient) ListAllPreparer() (*http.Request, error) { "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2017-03-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/network/watchers.go b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/watchers.go new file mode 100755 index 000000000000..28febf847484 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/network/watchers.go @@ -0,0 +1,1131 @@ +package network + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// WatchersClient is the composite Swagger for Network Client +type WatchersClient struct { + ManagementClient +} + +// NewWatchersClient creates an instance of the WatchersClient client. +func NewWatchersClient(subscriptionID string) WatchersClient { + return NewWatchersClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewWatchersClientWithBaseURI creates an instance of the WatchersClient +// client. +func NewWatchersClientWithBaseURI(baseURI string, subscriptionID string) WatchersClient { + return WatchersClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate creates or updates a network watcher in the specified +// resource group. +// +// resourceGroupName is the name of the resource group. networkWatcherName is +// the name of the network watcher. parameters is parameters that define the +// network watcher resource. +func (client WatchersClient) CreateOrUpdate(resourceGroupName string, networkWatcherName string, parameters Watcher) (result Watcher, err error) { + req, err := client.CreateOrUpdatePreparer(resourceGroupName, networkWatcherName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "network.WatchersClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.WatchersClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.WatchersClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client WatchersClient) CreateOrUpdatePreparer(resourceGroupName string, networkWatcherName string, parameters Watcher) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "networkWatcherName": autorest.Encode("path", networkWatcherName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client WatchersClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client WatchersClient) CreateOrUpdateResponder(resp *http.Response) (result Watcher, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes the specified network watcher resource. 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. networkWatcherName is +// the name of the network watcher. +func (client WatchersClient) Delete(resourceGroupName string, networkWatcherName string, cancel <-chan struct{}) (<-chan autorest.Response, <-chan error) { + resultChan := make(chan autorest.Response, 1) + errChan := make(chan error, 1) + go func() { + var err error + var result autorest.Response + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.DeletePreparer(resourceGroupName, networkWatcherName, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.WatchersClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "network.WatchersClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.WatchersClient", "Delete", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// DeletePreparer prepares the Delete request. +func (client WatchersClient) DeletePreparer(resourceGroupName string, networkWatcherName string, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "networkWatcherName": autorest.Encode("path", networkWatcherName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client WatchersClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client WatchersClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets the specified network watcher by resource group. +// +// resourceGroupName is the name of the resource group. networkWatcherName is +// the name of the network watcher. +func (client WatchersClient) Get(resourceGroupName string, networkWatcherName string) (result Watcher, err error) { + req, err := client.GetPreparer(resourceGroupName, networkWatcherName) + if err != nil { + err = autorest.NewErrorWithError(err, "network.WatchersClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.WatchersClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.WatchersClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client WatchersClient) GetPreparer(resourceGroupName string, networkWatcherName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "networkWatcherName": autorest.Encode("path", networkWatcherName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client WatchersClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client WatchersClient) GetResponder(resp *http.Response) (result Watcher, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetFlowLogStatus queries status of flow log on a specified resource. 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 network watcher resource group. +// networkWatcherName is the name of the network watcher resource. parameters +// is parameters that define a resource to query flow log status. +func (client WatchersClient) GetFlowLogStatus(resourceGroupName string, networkWatcherName string, parameters FlowLogStatusParameters, cancel <-chan struct{}) (<-chan FlowLogInformation, <-chan error) { + resultChan := make(chan FlowLogInformation, 1) + errChan := make(chan error, 1) + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.TargetResourceID", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + errChan <- validation.NewErrorWithValidationError(err, "network.WatchersClient", "GetFlowLogStatus") + close(errChan) + close(resultChan) + return resultChan, errChan + } + + go func() { + var err error + var result FlowLogInformation + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.GetFlowLogStatusPreparer(resourceGroupName, networkWatcherName, parameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetFlowLogStatus", nil, "Failure preparing request") + return + } + + resp, err := client.GetFlowLogStatusSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetFlowLogStatus", resp, "Failure sending request") + return + } + + result, err = client.GetFlowLogStatusResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetFlowLogStatus", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// GetFlowLogStatusPreparer prepares the GetFlowLogStatus request. +func (client WatchersClient) GetFlowLogStatusPreparer(resourceGroupName string, networkWatcherName string, parameters FlowLogStatusParameters, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "networkWatcherName": autorest.Encode("path", networkWatcherName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/queryFlowLogStatus", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// GetFlowLogStatusSender sends the GetFlowLogStatus request. The method will close the +// http.Response Body if it receives an error. +func (client WatchersClient) GetFlowLogStatusSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// GetFlowLogStatusResponder handles the response to the GetFlowLogStatus request. The method always +// closes the http.Response Body. +func (client WatchersClient) GetFlowLogStatusResponder(resp *http.Response) (result FlowLogInformation, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetNextHop gets the next hop from the specified VM. 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. networkWatcherName is +// the name of the network watcher. parameters is parameters that define the +// source and destination endpoint. +func (client WatchersClient) GetNextHop(resourceGroupName string, networkWatcherName string, parameters NextHopParameters, cancel <-chan struct{}) (<-chan NextHopResult, <-chan error) { + resultChan := make(chan NextHopResult, 1) + errChan := make(chan error, 1) + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.TargetResourceID", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.SourceIPAddress", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.DestinationIPAddress", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + errChan <- validation.NewErrorWithValidationError(err, "network.WatchersClient", "GetNextHop") + close(errChan) + close(resultChan) + return resultChan, errChan + } + + go func() { + var err error + var result NextHopResult + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.GetNextHopPreparer(resourceGroupName, networkWatcherName, parameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetNextHop", nil, "Failure preparing request") + return + } + + resp, err := client.GetNextHopSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetNextHop", resp, "Failure sending request") + return + } + + result, err = client.GetNextHopResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetNextHop", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// GetNextHopPreparer prepares the GetNextHop request. +func (client WatchersClient) GetNextHopPreparer(resourceGroupName string, networkWatcherName string, parameters NextHopParameters, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "networkWatcherName": autorest.Encode("path", networkWatcherName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/nextHop", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// GetNextHopSender sends the GetNextHop request. The method will close the +// http.Response Body if it receives an error. +func (client WatchersClient) GetNextHopSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// GetNextHopResponder handles the response to the GetNextHop request. The method always +// closes the http.Response Body. +func (client WatchersClient) GetNextHopResponder(resp *http.Response) (result NextHopResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetTopology gets the current network topology by resource group. +// +// resourceGroupName is the name of the resource group. networkWatcherName is +// the name of the network watcher. parameters is parameters that define the +// representation of topology. +func (client WatchersClient) GetTopology(resourceGroupName string, networkWatcherName string, parameters TopologyParameters) (result Topology, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.TargetResourceGroupName", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewErrorWithValidationError(err, "network.WatchersClient", "GetTopology") + } + + req, err := client.GetTopologyPreparer(resourceGroupName, networkWatcherName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetTopology", nil, "Failure preparing request") + return + } + + resp, err := client.GetTopologySender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetTopology", resp, "Failure sending request") + return + } + + result, err = client.GetTopologyResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetTopology", resp, "Failure responding to request") + } + + return +} + +// GetTopologyPreparer prepares the GetTopology request. +func (client WatchersClient) GetTopologyPreparer(resourceGroupName string, networkWatcherName string, parameters TopologyParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "networkWatcherName": autorest.Encode("path", networkWatcherName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/topology", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// GetTopologySender sends the GetTopology request. The method will close the +// http.Response Body if it receives an error. +func (client WatchersClient) GetTopologySender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// GetTopologyResponder handles the response to the GetTopology request. The method always +// closes the http.Response Body. +func (client WatchersClient) GetTopologyResponder(resp *http.Response) (result Topology, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetTroubleshooting initiate troubleshooting on a specified resource 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. networkWatcherName is +// the name of the network watcher resource. parameters is parameters that +// define the resource to troubleshoot. +func (client WatchersClient) GetTroubleshooting(resourceGroupName string, networkWatcherName string, parameters TroubleshootingParameters, cancel <-chan struct{}) (<-chan TroubleshootingResult, <-chan error) { + resultChan := make(chan TroubleshootingResult, 1) + errChan := make(chan error, 1) + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.TargetResourceID", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.TroubleshootingProperties", Name: validation.Null, Rule: true, + Chain: []validation.Constraint{{Target: "parameters.TroubleshootingProperties.StorageID", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.TroubleshootingProperties.StoragePath", Name: validation.Null, Rule: true, Chain: nil}, + }}}}}); err != nil { + errChan <- validation.NewErrorWithValidationError(err, "network.WatchersClient", "GetTroubleshooting") + close(errChan) + close(resultChan) + return resultChan, errChan + } + + go func() { + var err error + var result TroubleshootingResult + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.GetTroubleshootingPreparer(resourceGroupName, networkWatcherName, parameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetTroubleshooting", nil, "Failure preparing request") + return + } + + resp, err := client.GetTroubleshootingSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetTroubleshooting", resp, "Failure sending request") + return + } + + result, err = client.GetTroubleshootingResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetTroubleshooting", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// GetTroubleshootingPreparer prepares the GetTroubleshooting request. +func (client WatchersClient) GetTroubleshootingPreparer(resourceGroupName string, networkWatcherName string, parameters TroubleshootingParameters, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "networkWatcherName": autorest.Encode("path", networkWatcherName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/troubleshoot", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// GetTroubleshootingSender sends the GetTroubleshooting request. The method will close the +// http.Response Body if it receives an error. +func (client WatchersClient) GetTroubleshootingSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// GetTroubleshootingResponder handles the response to the GetTroubleshooting request. The method always +// closes the http.Response Body. +func (client WatchersClient) GetTroubleshootingResponder(resp *http.Response) (result TroubleshootingResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetTroubleshootingResult get the last completed troubleshooting result on a +// specified resource 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. networkWatcherName is +// the name of the network watcher resource. parameters is parameters that +// define the resource to query the troubleshooting result. +func (client WatchersClient) GetTroubleshootingResult(resourceGroupName string, networkWatcherName string, parameters QueryTroubleshootingParameters, cancel <-chan struct{}) (<-chan TroubleshootingResult, <-chan error) { + resultChan := make(chan TroubleshootingResult, 1) + errChan := make(chan error, 1) + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.TargetResourceID", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + errChan <- validation.NewErrorWithValidationError(err, "network.WatchersClient", "GetTroubleshootingResult") + close(errChan) + close(resultChan) + return resultChan, errChan + } + + go func() { + var err error + var result TroubleshootingResult + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.GetTroubleshootingResultPreparer(resourceGroupName, networkWatcherName, parameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetTroubleshootingResult", nil, "Failure preparing request") + return + } + + resp, err := client.GetTroubleshootingResultSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetTroubleshootingResult", resp, "Failure sending request") + return + } + + result, err = client.GetTroubleshootingResultResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetTroubleshootingResult", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// GetTroubleshootingResultPreparer prepares the GetTroubleshootingResult request. +func (client WatchersClient) GetTroubleshootingResultPreparer(resourceGroupName string, networkWatcherName string, parameters QueryTroubleshootingParameters, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "networkWatcherName": autorest.Encode("path", networkWatcherName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/queryTroubleshootResult", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// GetTroubleshootingResultSender sends the GetTroubleshootingResult request. The method will close the +// http.Response Body if it receives an error. +func (client WatchersClient) GetTroubleshootingResultSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// GetTroubleshootingResultResponder handles the response to the GetTroubleshootingResult request. The method always +// closes the http.Response Body. +func (client WatchersClient) GetTroubleshootingResultResponder(resp *http.Response) (result TroubleshootingResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetVMSecurityRules gets the configured and effective security group rules on +// the specified VM. 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. networkWatcherName is +// the name of the network watcher. parameters is parameters that define the VM +// to check security groups for. +func (client WatchersClient) GetVMSecurityRules(resourceGroupName string, networkWatcherName string, parameters SecurityGroupViewParameters, cancel <-chan struct{}) (<-chan SecurityGroupViewResult, <-chan error) { + resultChan := make(chan SecurityGroupViewResult, 1) + errChan := make(chan error, 1) + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.TargetResourceID", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + errChan <- validation.NewErrorWithValidationError(err, "network.WatchersClient", "GetVMSecurityRules") + close(errChan) + close(resultChan) + return resultChan, errChan + } + + go func() { + var err error + var result SecurityGroupViewResult + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.GetVMSecurityRulesPreparer(resourceGroupName, networkWatcherName, parameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetVMSecurityRules", nil, "Failure preparing request") + return + } + + resp, err := client.GetVMSecurityRulesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetVMSecurityRules", resp, "Failure sending request") + return + } + + result, err = client.GetVMSecurityRulesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.WatchersClient", "GetVMSecurityRules", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// GetVMSecurityRulesPreparer prepares the GetVMSecurityRules request. +func (client WatchersClient) GetVMSecurityRulesPreparer(resourceGroupName string, networkWatcherName string, parameters SecurityGroupViewParameters, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "networkWatcherName": autorest.Encode("path", networkWatcherName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/securityGroupView", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// GetVMSecurityRulesSender sends the GetVMSecurityRules request. The method will close the +// http.Response Body if it receives an error. +func (client WatchersClient) GetVMSecurityRulesSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// GetVMSecurityRulesResponder handles the response to the GetVMSecurityRules request. The method always +// closes the http.Response Body. +func (client WatchersClient) GetVMSecurityRulesResponder(resp *http.Response) (result SecurityGroupViewResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List gets all network watchers by resource group. +// +// resourceGroupName is the name of the resource group. +func (client WatchersClient) List(resourceGroupName string) (result WatcherListResult, err error) { + req, err := client.ListPreparer(resourceGroupName) + if err != nil { + err = autorest.NewErrorWithError(err, "network.WatchersClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.WatchersClient", "List", resp, "Failure sending request") + return + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.WatchersClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client WatchersClient) ListPreparer(resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client WatchersClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client WatchersClient) ListResponder(resp *http.Response) (result WatcherListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListAll gets all network watchers by subscription. +func (client WatchersClient) ListAll() (result WatcherListResult, err error) { + req, err := client.ListAllPreparer() + if err != nil { + err = autorest.NewErrorWithError(err, "network.WatchersClient", "ListAll", nil, "Failure preparing request") + return + } + + resp, err := client.ListAllSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.WatchersClient", "ListAll", resp, "Failure sending request") + return + } + + result, err = client.ListAllResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.WatchersClient", "ListAll", resp, "Failure responding to request") + } + + return +} + +// ListAllPreparer prepares the ListAll request. +func (client WatchersClient) ListAllPreparer() (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkWatchers", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListAllSender sends the ListAll request. The method will close the +// http.Response Body if it receives an error. +func (client WatchersClient) ListAllSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListAllResponder handles the response to the ListAll request. The method always +// closes the http.Response Body. +func (client WatchersClient) ListAllResponder(resp *http.Response) (result WatcherListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// SetFlowLogConfiguration configures flow log on a specified resource. 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 network watcher resource group. +// networkWatcherName is the name of the network watcher resource. parameters +// is parameters that define the configuration of flow log. +func (client WatchersClient) SetFlowLogConfiguration(resourceGroupName string, networkWatcherName string, parameters FlowLogInformation, cancel <-chan struct{}) (<-chan FlowLogInformation, <-chan error) { + resultChan := make(chan FlowLogInformation, 1) + errChan := make(chan error, 1) + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.TargetResourceID", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.FlowLogProperties", Name: validation.Null, Rule: true, + Chain: []validation.Constraint{{Target: "parameters.FlowLogProperties.StorageID", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.FlowLogProperties.Enabled", Name: validation.Null, Rule: true, Chain: nil}, + }}}}}); err != nil { + errChan <- validation.NewErrorWithValidationError(err, "network.WatchersClient", "SetFlowLogConfiguration") + close(errChan) + close(resultChan) + return resultChan, errChan + } + + go func() { + var err error + var result FlowLogInformation + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.SetFlowLogConfigurationPreparer(resourceGroupName, networkWatcherName, parameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.WatchersClient", "SetFlowLogConfiguration", nil, "Failure preparing request") + return + } + + resp, err := client.SetFlowLogConfigurationSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.WatchersClient", "SetFlowLogConfiguration", resp, "Failure sending request") + return + } + + result, err = client.SetFlowLogConfigurationResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.WatchersClient", "SetFlowLogConfiguration", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// SetFlowLogConfigurationPreparer prepares the SetFlowLogConfiguration request. +func (client WatchersClient) SetFlowLogConfigurationPreparer(resourceGroupName string, networkWatcherName string, parameters FlowLogInformation, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "networkWatcherName": autorest.Encode("path", networkWatcherName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/configureFlowLog", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// SetFlowLogConfigurationSender sends the SetFlowLogConfiguration request. The method will close the +// http.Response Body if it receives an error. +func (client WatchersClient) SetFlowLogConfigurationSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// SetFlowLogConfigurationResponder handles the response to the SetFlowLogConfiguration request. The method always +// closes the http.Response Body. +func (client WatchersClient) SetFlowLogConfigurationResponder(resp *http.Response) (result FlowLogInformation, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// VerifyIPFlow verify IP flow from the specified VM to a location given the +// currently configured NSG rules. 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. networkWatcherName is +// the name of the network watcher. parameters is parameters that define the IP +// flow to be verified. +func (client WatchersClient) VerifyIPFlow(resourceGroupName string, networkWatcherName string, parameters VerificationIPFlowParameters, cancel <-chan struct{}) (<-chan VerificationIPFlowResult, <-chan error) { + resultChan := make(chan VerificationIPFlowResult, 1) + errChan := make(chan error, 1) + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.TargetResourceID", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.LocalPort", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.RemotePort", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.LocalIPAddress", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.RemoteIPAddress", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + errChan <- validation.NewErrorWithValidationError(err, "network.WatchersClient", "VerifyIPFlow") + close(errChan) + close(resultChan) + return resultChan, errChan + } + + go func() { + var err error + var result VerificationIPFlowResult + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.VerifyIPFlowPreparer(resourceGroupName, networkWatcherName, parameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "network.WatchersClient", "VerifyIPFlow", nil, "Failure preparing request") + return + } + + resp, err := client.VerifyIPFlowSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "network.WatchersClient", "VerifyIPFlow", resp, "Failure sending request") + return + } + + result, err = client.VerifyIPFlowResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "network.WatchersClient", "VerifyIPFlow", resp, "Failure responding to request") + } + }() + return resultChan, errChan +} + +// VerifyIPFlowPreparer prepares the VerifyIPFlow request. +func (client WatchersClient) VerifyIPFlowPreparer(resourceGroupName string, networkWatcherName string, parameters VerificationIPFlowParameters, cancel <-chan struct{}) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "networkWatcherName": autorest.Encode("path", networkWatcherName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-03-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/ipFlowVerify", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{Cancel: cancel}) +} + +// VerifyIPFlowSender sends the VerifyIPFlow request. The method will close the +// http.Response Body if it receives an error. +func (client WatchersClient) VerifyIPFlowSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, + req, + azure.DoPollForAsynchronous(client.PollingDelay)) +} + +// VerifyIPFlowResponder handles the response to the VerifyIPFlow request. The method always +// closes the http.Response Body. +func (client WatchersClient) VerifyIPFlowResponder(resp *http.Response) (result VerificationIPFlowResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/arm/storage/BUILD b/vendor/github.com/Azure/azure-sdk-for-go/arm/storage/BUILD index dd7d10054d78..f7c2637c556b 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/storage/BUILD +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/storage/BUILD @@ -13,7 +13,7 @@ go_library( "accounts.go", "client.go", "models.go", - "usageoperations.go", + "usage.go", "version.go", ], tags = ["automanaged"], 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 old mode 100644 new mode 100755 index c895c3a949f1..f0606ac133f3 --- 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,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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -25,7 +25,7 @@ import ( "net/http" ) -// AccountsClient is the the Storage Management Client. +// AccountsClient is the the Azure Storage Management API. type AccountsClient struct { ManagementClient } @@ -44,9 +44,9 @@ func NewAccountsClientWithBaseURI(baseURI string, subscriptionID string) Account // CheckNameAvailability checks that the storage account name is valid and is // not already in use. // -// 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. +// 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, err error) { if err := validation.Validate([]validation.Validation{ {TargetValue: accountName, @@ -57,13 +57,15 @@ func (client AccountsClient) CheckNameAvailability(accountName AccountCheckNameA req, err := client.CheckNameAvailabilityPreparer(accountName) if err != nil { - return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "CheckNameAvailability", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "CheckNameAvailability", nil, "Failure preparing request") + return } resp, err := client.CheckNameAvailabilitySender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "CheckNameAvailability", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "CheckNameAvailability", resp, "Failure sending request") + return } result, err = client.CheckNameAvailabilityResponder(resp) @@ -80,8 +82,9 @@ func (client AccountsClient) CheckNameAvailabilityPreparer(accountName AccountCh "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2016-12-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -114,59 +117,74 @@ func (client AccountsClient) CheckNameAvailabilityResponder(resp *http.Response) } // Create asynchronously creates a new storage account with the specified -// parameters. If an account is already created and a subsequent create -// request is issued with different properties, the account properties will -// be updated. If an account is already created and a subsequent create or -// update request is issued with the exact same set of properties, the -// request will succeed. 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. +// parameters. If an account is already created and a subsequent create request +// is issued with different properties, the account properties will be updated. +// If an account is already created and a subsequent create or update request +// is issued with the exact same set of properties, the request will succeed. +// 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, cancel <-chan struct{}) (result autorest.Response, err error) { +// subscription. The name is case insensitive. 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, cancel <-chan struct{}) (<-chan Account, <-chan error) { + resultChan := make(chan Account, 1) + errChan := make(chan error, 1) if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, {TargetValue: accountName, Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}}}, {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.Sku", Name: validation.Null, Rule: true, - Chain: []validation.Constraint{{Target: "parameters.Sku.Tier", Name: validation.ReadOnly, Rule: true, Chain: nil}}}, + Constraints: []validation.Constraint{{Target: "parameters.Sku", Name: validation.Null, Rule: true, Chain: nil}, {Target: "parameters.Location", Name: validation.Null, Rule: true, Chain: nil}, {Target: "parameters.AccountPropertiesCreateParameters", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "parameters.AccountPropertiesCreateParameters.CustomDomain", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "parameters.AccountPropertiesCreateParameters.CustomDomain.Name", Name: validation.Null, Rule: true, Chain: nil}}}, {Target: "parameters.AccountPropertiesCreateParameters.Encryption", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.AccountPropertiesCreateParameters.Encryption.Services", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.AccountPropertiesCreateParameters.Encryption.Services.Blob", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.AccountPropertiesCreateParameters.Encryption.Services.Blob.LastEnabledTime", Name: validation.ReadOnly, Rule: true, Chain: nil}}}, - }}, - {Target: "parameters.AccountPropertiesCreateParameters.Encryption.KeySource", Name: validation.Null, Rule: true, Chain: nil}, - }}, + Chain: []validation.Constraint{{Target: "parameters.AccountPropertiesCreateParameters.Encryption.KeySource", Name: validation.Null, Rule: true, Chain: nil}}}, }}}}}); err != nil { - return result, validation.NewErrorWithValidationError(err, "storage.AccountsClient", "Create") - } - - req, err := client.CreatePreparer(resourceGroupName, accountName, parameters, cancel) - if err != nil { - return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "Create", nil, "Failure preparing request") - } - - resp, err := client.CreateSender(req) - if err != nil { - result.Response = resp - return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "Create", resp, "Failure sending request") - } - - result, err = client.CreateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "storage.AccountsClient", "Create", resp, "Failure responding to request") - } - - return + errChan <- validation.NewErrorWithValidationError(err, "storage.AccountsClient", "Create") + close(errChan) + close(resultChan) + return resultChan, errChan + } + + go func() { + var err error + var result Account + defer func() { + resultChan <- result + errChan <- err + close(resultChan) + close(errChan) + }() + req, err := client.CreatePreparer(resourceGroupName, accountName, parameters, cancel) + if err != nil { + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "Create", nil, "Failure preparing request") + return + } + + resp, err := client.CreateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "Create", resp, "Failure sending request") + return + } + + result, err = client.CreateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "Create", resp, "Failure responding to request") + } + }() + return resultChan, errChan } // CreatePreparer prepares the Create request. @@ -177,8 +195,9 @@ func (client AccountsClient) CreatePreparer(resourceGroupName string, accountNam "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2016-12-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -201,24 +220,30 @@ func (client AccountsClient) CreateSender(req *http.Request) (*http.Response, er // CreateResponder handles the response to the Create request. The method always // closes the http.Response Body. -func (client AccountsClient) CreateResponder(resp *http.Response) (result autorest.Response, err error) { +func (client AccountsClient) CreateResponder(resp *http.Response) (result Account, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) - result.Response = resp + result.Response = autorest.Response{Response: resp} return } // Delete deletes a storage account in Microsoft Azure. // // 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. +// subscription. The name is case insensitive. 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, err error) { if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, {TargetValue: accountName, Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}}}}); err != nil { @@ -227,13 +252,15 @@ func (client AccountsClient) Delete(resourceGroupName string, accountName string req, err := client.DeletePreparer(resourceGroupName, accountName) if err != nil { - return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "Delete", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "Delete", nil, "Failure preparing request") + return } resp, err := client.DeleteSender(req) if err != nil { result.Response = resp - return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "Delete", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "Delete", resp, "Failure sending request") + return } result, err = client.DeleteResponder(resp) @@ -252,8 +279,9 @@ func (client AccountsClient) DeletePreparer(resourceGroupName string, accountNam "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2016-12-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -287,11 +315,16 @@ func (client AccountsClient) DeleteResponder(resp *http.Response) (result autore // The ListKeys operation should be used to retrieve storage keys. // // 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. +// subscription. The name is case insensitive. 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, err error) { if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, {TargetValue: accountName, Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}}}}); err != nil { @@ -300,13 +333,15 @@ func (client AccountsClient) GetProperties(resourceGroupName string, accountName req, err := client.GetPropertiesPreparer(resourceGroupName, accountName) if err != nil { - return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "GetProperties", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "GetProperties", nil, "Failure preparing request") + return } resp, err := client.GetPropertiesSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "GetProperties", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "GetProperties", resp, "Failure sending request") + return } result, err = client.GetPropertiesResponder(resp) @@ -325,8 +360,9 @@ func (client AccountsClient) GetPropertiesPreparer(resourceGroupName string, acc "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2016-12-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -361,13 +397,15 @@ func (client AccountsClient) GetPropertiesResponder(resp *http.Response) (result func (client AccountsClient) List() (result AccountListResult, err error) { req, err := client.ListPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "List", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "List", nil, "Failure preparing request") + return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "List", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "List", resp, "Failure sending request") + return } result, err = client.ListResponder(resp) @@ -384,8 +422,9 @@ func (client AccountsClient) ListPreparer() (*http.Request, error) { "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2016-12-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -415,22 +454,117 @@ func (client AccountsClient) ListResponder(resp *http.Response) (result AccountL return } -// ListByResourceGroup lists all the storage accounts available under the -// given resource group. Note that storage keys are not returned; use the -// ListKeys operation for this. +// ListAccountSAS list SAS credentials of a storage account. // // resourceGroupName is the name of the resource group within the user's -// subscription. +// subscription. The name is case insensitive. 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 to list SAS +// credentials for the storage account. +func (client AccountsClient) ListAccountSAS(resourceGroupName string, accountName string, parameters AccountSasParameters) (result ListAccountSasResponse, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}}}, + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.SharedAccessExpiryTime", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewErrorWithValidationError(err, "storage.AccountsClient", "ListAccountSAS") + } + + req, err := client.ListAccountSASPreparer(resourceGroupName, accountName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "ListAccountSAS", nil, "Failure preparing request") + return + } + + resp, err := client.ListAccountSASSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "ListAccountSAS", resp, "Failure sending request") + return + } + + result, err = client.ListAccountSASResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "ListAccountSAS", resp, "Failure responding to request") + } + + return +} + +// ListAccountSASPreparer prepares the ListAccountSAS request. +func (client AccountsClient) ListAccountSASPreparer(resourceGroupName string, accountName string, parameters AccountSasParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-12-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/ListAccountSas", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListAccountSASSender sends the ListAccountSAS request. The method will close the +// http.Response Body if it receives an error. +func (client AccountsClient) ListAccountSASSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListAccountSASResponder handles the response to the ListAccountSAS request. The method always +// closes the http.Response Body. +func (client AccountsClient) ListAccountSASResponder(resp *http.Response) (result ListAccountSasResponse, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByResourceGroup lists all the storage accounts available under the given +// resource group. Note that storage keys are not returned; use the ListKeys +// operation for this. +// +// resourceGroupName is the name of the resource group within the user's +// subscription. The name is case insensitive. func (client AccountsClient) ListByResourceGroup(resourceGroupName string) (result AccountListResult, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { + return result, validation.NewErrorWithValidationError(err, "storage.AccountsClient", "ListByResourceGroup") + } + req, err := client.ListByResourceGroupPreparer(resourceGroupName) if err != nil { - return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "ListByResourceGroup", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "ListByResourceGroup", nil, "Failure preparing request") + return } resp, err := client.ListByResourceGroupSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "ListByResourceGroup", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "ListByResourceGroup", resp, "Failure sending request") + return } result, err = client.ListByResourceGroupResponder(resp) @@ -448,8 +582,9 @@ func (client AccountsClient) ListByResourceGroupPreparer(resourceGroupName strin "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2016-12-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -482,11 +617,16 @@ func (client AccountsClient) ListByResourceGroupResponder(resp *http.Response) ( // ListKeys lists the access keys for the specified storage account. // // 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. +// subscription. The name is case insensitive. 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) ListKeys(resourceGroupName string, accountName string) (result AccountListKeysResult, err error) { if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, {TargetValue: accountName, Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}}}}); err != nil { @@ -495,13 +635,15 @@ func (client AccountsClient) ListKeys(resourceGroupName string, accountName stri req, err := client.ListKeysPreparer(resourceGroupName, accountName) if err != nil { - return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "ListKeys", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "ListKeys", nil, "Failure preparing request") + return } resp, err := client.ListKeysSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "ListKeys", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "ListKeys", resp, "Failure sending request") + return } result, err = client.ListKeysResponder(resp) @@ -520,8 +662,9 @@ func (client AccountsClient) ListKeysPreparer(resourceGroupName string, accountN "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2016-12-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -551,17 +694,108 @@ func (client AccountsClient) ListKeysResponder(resp *http.Response) (result Acco return } +// ListServiceSAS list service SAS credentials of a specific resource. +// +// resourceGroupName is the name of the resource group within the user's +// subscription. The name is case insensitive. 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 to list service SAS +// credentials. +func (client AccountsClient) ListServiceSAS(resourceGroupName string, accountName string, parameters ServiceSasParameters) (result ListServiceSasResponse, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, + {TargetValue: accountName, + Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, + {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}}}, + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.CanonicalizedResource", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.Identifier", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.Identifier", Name: validation.MaxLength, Rule: 64, Chain: nil}}}}}}); err != nil { + return result, validation.NewErrorWithValidationError(err, "storage.AccountsClient", "ListServiceSAS") + } + + req, err := client.ListServiceSASPreparer(resourceGroupName, accountName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "ListServiceSAS", nil, "Failure preparing request") + return + } + + resp, err := client.ListServiceSASSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "ListServiceSAS", resp, "Failure sending request") + return + } + + result, err = client.ListServiceSASResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "ListServiceSAS", resp, "Failure responding to request") + } + + return +} + +// ListServiceSASPreparer prepares the ListServiceSAS request. +func (client AccountsClient) ListServiceSASPreparer(resourceGroupName string, accountName string, parameters ServiceSasParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "accountName": autorest.Encode("path", accountName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-12-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsJSON(), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/ListServiceSas", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare(&http.Request{}) +} + +// ListServiceSASSender sends the ListServiceSAS request. The method will close the +// http.Response Body if it receives an error. +func (client AccountsClient) ListServiceSASSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req) +} + +// ListServiceSASResponder handles the response to the ListServiceSAS request. The method always +// closes the http.Response Body. +func (client AccountsClient) ListServiceSASResponder(resp *http.Response) (result ListServiceSasResponse, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + // RegenerateKey regenerates one of the access keys for the specified storage // account. // // 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. -// regenerateKey is specifies name of the key which should be regenerated -- -// key1 or key2. +// subscription. The name is case insensitive. 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. regenerateKey is specifies name of the key which should be +// regenerated -- key1 or key2. func (client AccountsClient) RegenerateKey(resourceGroupName string, accountName string, regenerateKey AccountRegenerateKeyParameters) (result AccountListKeysResult, err error) { if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, {TargetValue: accountName, Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}}}, @@ -572,13 +806,15 @@ func (client AccountsClient) RegenerateKey(resourceGroupName string, accountName req, err := client.RegenerateKeyPreparer(resourceGroupName, accountName, regenerateKey) if err != nil { - return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "RegenerateKey", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "RegenerateKey", nil, "Failure preparing request") + return } resp, err := client.RegenerateKeySender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "RegenerateKey", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "RegenerateKey", resp, "Failure sending request") + return } result, err = client.RegenerateKeyResponder(resp) @@ -597,8 +833,9 @@ func (client AccountsClient) RegenerateKeyPreparer(resourceGroupName string, acc "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2016-12-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -632,22 +869,27 @@ func (client AccountsClient) RegenerateKeyResponder(resp *http.Response) (result // Update the update operation can be used to update the SKU, encryption, // access tier, or tags for a storage account. It can also be used to map the -// account to a custom domain. Only one custom domain is supported per -// storage account; the replacement/change of custom domain is not supported. -// In order to replace an old custom domain, the old value must be -// cleared/unregistered before a new value can be set. The update of multiple -// properties is supported. This call does not change the storage keys for -// the account. If you want to change the storage account keys, use the -// regenerate keys operation. The location and name of the storage account -// cannot be changed after creation. +// account to a custom domain. Only one custom domain is supported per storage +// account; the replacement/change of custom domain is not supported. In order +// to replace an old custom domain, the old value must be cleared/unregistered +// before a new value can be set. The update of multiple properties is +// supported. This call does not change the storage keys for the account. If +// you want to change the storage account keys, use the regenerate keys +// operation. The location and name of the storage account cannot be changed +// after creation. // // 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 updated account. +// subscription. The name is case insensitive. 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 updated +// account. func (client AccountsClient) Update(resourceGroupName string, accountName string, parameters AccountUpdateParameters) (result Account, err error) { if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, + {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, {TargetValue: accountName, Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 24, Chain: nil}, {Target: "accountName", Name: validation.MinLength, Rule: 3, Chain: nil}}}}); err != nil { @@ -656,13 +898,15 @@ func (client AccountsClient) Update(resourceGroupName string, accountName string req, err := client.UpdatePreparer(resourceGroupName, accountName, parameters) if err != nil { - return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "Update", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "Update", nil, "Failure preparing request") + return } resp, err := client.UpdateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "storage.AccountsClient", "Update", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "storage.AccountsClient", "Update", resp, "Failure sending request") + return } result, err = client.UpdateResponder(resp) @@ -681,8 +925,9 @@ func (client AccountsClient) UpdatePreparer(resourceGroupName string, accountNam "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2016-12-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( 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 old mode 100644 new mode 100755 index 68708dbf243e..a537bdd25ec0 --- 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,7 +1,7 @@ // Package storage implements the Azure ARM Storage service API version -// 2016-01-01. +// 2016-12-01. // -// The Storage Management Client. +// The Azure Storage Management API. package storage // Copyright (c) Microsoft and contributors. All rights reserved. @@ -18,7 +18,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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -27,9 +27,6 @@ import ( ) const ( - // APIVersion is the version of the Storage - APIVersion = "2016-01-01" - // DefaultBaseURI is the default URI used for the service Storage DefaultBaseURI = "https://management.azure.com" ) @@ -38,7 +35,6 @@ const ( type ManagementClient struct { autorest.Client BaseURI string - APIVersion string SubscriptionID string } @@ -52,7 +48,6 @@ func NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient { return ManagementClient{ Client: autorest.NewClientWithUserAgent(UserAgent()), BaseURI: baseURI, - APIVersion: APIVersion, SubscriptionID: subscriptionID, } } 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 old mode 100644 new mode 100755 index bff65ec6eb5c..2e203018428e --- 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,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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -38,19 +38,29 @@ type AccountStatus string const ( // Available specifies the available state for account status. - Available AccountStatus = "Available" + Available AccountStatus = "available" // Unavailable specifies the unavailable state for account status. - Unavailable AccountStatus = "Unavailable" + Unavailable AccountStatus = "unavailable" +) + +// HTTPProtocol enumerates the values for http protocol. +type HTTPProtocol string + +const ( + // HTTPS specifies the https state for http protocol. + HTTPS HTTPProtocol = "https" + // Httpshttp specifies the httpshttp state for http protocol. + Httpshttp HTTPProtocol = "https,http" ) // KeyPermission enumerates the values for key permission. type KeyPermission string const ( - // FULL specifies the full state for key permission. - FULL KeyPermission = "FULL" - // READ specifies the read state for key permission. - READ KeyPermission = "READ" + // Full specifies the full state for key permission. + Full KeyPermission = "Full" + // Read specifies the read state for key permission. + Read KeyPermission = "Read" ) // Kind enumerates the values for kind. @@ -63,6 +73,50 @@ const ( Storage Kind = "Storage" ) +// Permissions enumerates the values for permissions. +type Permissions string + +const ( + // A specifies the a state for permissions. + A Permissions = "a" + // C specifies the c state for permissions. + C Permissions = "c" + // D specifies the d state for permissions. + D Permissions = "d" + // L specifies the l state for permissions. + L Permissions = "l" + // P specifies the p state for permissions. + P Permissions = "p" + // R specifies the r state for permissions. + R Permissions = "r" + // U specifies the u state for permissions. + U Permissions = "u" + // W specifies the w state for permissions. + W Permissions = "w" +) + +// Permissions1 enumerates the values for permissions 1. +type Permissions1 string + +const ( + // Permissions1A specifies the permissions 1a state for permissions 1. + Permissions1A Permissions1 = "a" + // Permissions1C specifies the permissions 1c state for permissions 1. + Permissions1C Permissions1 = "c" + // Permissions1D specifies the permissions 1d state for permissions 1. + Permissions1D Permissions1 = "d" + // Permissions1L specifies the permissions 1l state for permissions 1. + Permissions1L Permissions1 = "l" + // Permissions1P specifies the permissions 1p state for permissions 1. + Permissions1P Permissions1 = "p" + // Permissions1R specifies the permissions 1r state for permissions 1. + Permissions1R Permissions1 = "r" + // Permissions1U specifies the permissions 1u state for permissions 1. + Permissions1U Permissions1 = "u" + // Permissions1W specifies the permissions 1w state for permissions 1. + Permissions1W Permissions1 = "w" +) + // ProvisioningState enumerates the values for provisioning state. type ProvisioningState string @@ -85,6 +139,46 @@ const ( AlreadyExists Reason = "AlreadyExists" ) +// ResourceEnum enumerates the values for resource enum. +type ResourceEnum string + +const ( + // ResourceEnumB specifies the resource enum b state for resource enum. + ResourceEnumB ResourceEnum = "b" + // ResourceEnumC specifies the resource enum c state for resource enum. + ResourceEnumC ResourceEnum = "c" + // ResourceEnumF specifies the resource enum f state for resource enum. + ResourceEnumF ResourceEnum = "f" + // ResourceEnumS specifies the resource enum s state for resource enum. + ResourceEnumS ResourceEnum = "s" +) + +// ResourceTypes enumerates the values for resource types. +type ResourceTypes string + +const ( + // ResourceTypesC specifies the resource types c state for resource types. + ResourceTypesC ResourceTypes = "c" + // ResourceTypesO specifies the resource types o state for resource types. + ResourceTypesO ResourceTypes = "o" + // ResourceTypesS specifies the resource types s state for resource types. + ResourceTypesS ResourceTypes = "s" +) + +// Services enumerates the values for services. +type Services string + +const ( + // B specifies the b state for services. + B Services = "b" + // F specifies the f state for services. + F Services = "f" + // Q specifies the q state for services. + Q Services = "q" + // T specifies the t state for services. + T Services = "t" +) + // SkuName enumerates the values for sku name. type SkuName string @@ -142,7 +236,8 @@ type Account struct { *AccountProperties `json:"properties,omitempty"` } -// AccountCheckNameAvailabilityParameters is +// AccountCheckNameAvailabilityParameters is the parameters used to check the +// availabity of the storage account name. type AccountCheckNameAvailabilityParameters struct { Name *string `json:"name,omitempty"` Type *string `json:"type,omitempty"` @@ -177,43 +272,62 @@ type AccountListResult struct { Value *[]Account `json:"value,omitempty"` } -// AccountProperties is +// AccountProperties is properties of the storage account. type AccountProperties struct { - ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` - PrimaryEndpoints *Endpoints `json:"primaryEndpoints,omitempty"` - PrimaryLocation *string `json:"primaryLocation,omitempty"` - StatusOfPrimary AccountStatus `json:"statusOfPrimary,omitempty"` - LastGeoFailoverTime *date.Time `json:"lastGeoFailoverTime,omitempty"` - SecondaryLocation *string `json:"secondaryLocation,omitempty"` - StatusOfSecondary AccountStatus `json:"statusOfSecondary,omitempty"` - CreationTime *date.Time `json:"creationTime,omitempty"` - CustomDomain *CustomDomain `json:"customDomain,omitempty"` - SecondaryEndpoints *Endpoints `json:"secondaryEndpoints,omitempty"` - Encryption *Encryption `json:"encryption,omitempty"` - AccessTier AccessTier `json:"accessTier,omitempty"` + ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` + PrimaryEndpoints *Endpoints `json:"primaryEndpoints,omitempty"` + PrimaryLocation *string `json:"primaryLocation,omitempty"` + StatusOfPrimary AccountStatus `json:"statusOfPrimary,omitempty"` + LastGeoFailoverTime *date.Time `json:"lastGeoFailoverTime,omitempty"` + SecondaryLocation *string `json:"secondaryLocation,omitempty"` + StatusOfSecondary AccountStatus `json:"statusOfSecondary,omitempty"` + CreationTime *date.Time `json:"creationTime,omitempty"` + CustomDomain *CustomDomain `json:"customDomain,omitempty"` + SecondaryEndpoints *Endpoints `json:"secondaryEndpoints,omitempty"` + Encryption *Encryption `json:"encryption,omitempty"` + AccessTier AccessTier `json:"accessTier,omitempty"` + EnableHTTPSTrafficOnly *bool `json:"supportsHttpsTrafficOnly,omitempty"` } -// AccountPropertiesCreateParameters is +// AccountPropertiesCreateParameters is the parameters used to create the +// storage account. type AccountPropertiesCreateParameters struct { - CustomDomain *CustomDomain `json:"customDomain,omitempty"` - Encryption *Encryption `json:"encryption,omitempty"` - AccessTier AccessTier `json:"accessTier,omitempty"` + CustomDomain *CustomDomain `json:"customDomain,omitempty"` + Encryption *Encryption `json:"encryption,omitempty"` + AccessTier AccessTier `json:"accessTier,omitempty"` + EnableHTTPSTrafficOnly *bool `json:"supportsHttpsTrafficOnly,omitempty"` } -// AccountPropertiesUpdateParameters is +// AccountPropertiesUpdateParameters is the parameters used when updating a +// storage account. type AccountPropertiesUpdateParameters struct { - CustomDomain *CustomDomain `json:"customDomain,omitempty"` - Encryption *Encryption `json:"encryption,omitempty"` - AccessTier AccessTier `json:"accessTier,omitempty"` + CustomDomain *CustomDomain `json:"customDomain,omitempty"` + Encryption *Encryption `json:"encryption,omitempty"` + AccessTier AccessTier `json:"accessTier,omitempty"` + EnableHTTPSTrafficOnly *bool `json:"supportsHttpsTrafficOnly,omitempty"` } -// AccountRegenerateKeyParameters is +// AccountRegenerateKeyParameters is the parameters used to regenerate the +// storage account key. type AccountRegenerateKeyParameters struct { KeyName *string `json:"keyName,omitempty"` } -// AccountUpdateParameters is the parameters that can be provided when -// updating the storage account properties. +// AccountSasParameters is the parameters to list SAS credentials of a storage +// account. +type AccountSasParameters struct { + Services Services `json:"signedServices,omitempty"` + ResourceTypes ResourceTypes `json:"signedResourceTypes,omitempty"` + Permissions Permissions `json:"signedPermission,omitempty"` + IPAddressOrRange *string `json:"signedIp,omitempty"` + Protocols HTTPProtocol `json:"signedProtocol,omitempty"` + SharedAccessStartTime *date.Time `json:"signedStart,omitempty"` + SharedAccessExpiryTime *date.Time `json:"signedExpiry,omitempty"` + KeyToSign *string `json:"keyToSign,omitempty"` +} + +// AccountUpdateParameters is the parameters that can be provided when updating +// the storage account properties. type AccountUpdateParameters struct { Sku *Sku `json:"sku,omitempty"` Tags *map[string]*string `json:"tags,omitempty"` @@ -228,8 +342,8 @@ type CheckNameAvailabilityResult struct { Message *string `json:"message,omitempty"` } -// CustomDomain is the custom domain assigned to this storage account. This -// can be set via Update. +// CustomDomain is the custom domain assigned to this storage account. This can +// be set via Update. type CustomDomain struct { Name *string `json:"name,omitempty"` UseSubDomain *bool `json:"useSubDomain,omitempty"` @@ -250,11 +364,14 @@ type EncryptionService struct { // EncryptionServices is a list of services that support encryption. type EncryptionServices struct { - Blob *EncryptionService `json:"blob,omitempty"` + Blob *EncryptionService `json:"blob,omitempty"` + File *EncryptionService `json:"file,omitempty"` + Table *EncryptionService `json:"table,omitempty"` + Queue *EncryptionService `json:"queue,omitempty"` } -// Endpoints is the URIs that are used to perform a retrieval of a public -// blob, queue, or table object. +// Endpoints is the URIs that are used to perform a retrieval of a public blob, +// queue, or table object. type Endpoints struct { Blob *string `json:"blob,omitempty"` Queue *string `json:"queue,omitempty"` @@ -262,7 +379,20 @@ type Endpoints struct { File *string `json:"file,omitempty"` } -// Resource is +// ListAccountSasResponse is the List SAS credentials operation response. +type ListAccountSasResponse struct { + autorest.Response `json:"-"` + AccountSasToken *string `json:"accountSasToken,omitempty"` +} + +// ListServiceSasResponse is the List service SAS credentials operation +// response. +type ListServiceSasResponse struct { + autorest.Response `json:"-"` + ServiceSasToken *string `json:"serviceSasToken,omitempty"` +} + +// Resource is describes a storage resource. type Resource struct { ID *string `json:"id,omitempty"` Name *string `json:"name,omitempty"` @@ -271,6 +401,29 @@ type Resource struct { Tags *map[string]*string `json:"tags,omitempty"` } +// ServiceSasParameters is the parameters to list service SAS credentials of a +// speicific resource. +type ServiceSasParameters struct { + CanonicalizedResource *string `json:"canonicalizedResource,omitempty"` + Resource Resource `json:"signedResource,omitempty"` + Permissions Permissions `json:"signedPermission,omitempty"` + IPAddressOrRange *string `json:"signedIp,omitempty"` + Protocols HTTPProtocol `json:"signedProtocol,omitempty"` + SharedAccessStartTime *date.Time `json:"signedStart,omitempty"` + SharedAccessExpiryTime *date.Time `json:"signedExpiry,omitempty"` + Identifier *string `json:"signedIdentifier,omitempty"` + PartitionKeyStart *string `json:"startPk,omitempty"` + PartitionKeyEnd *string `json:"endPk,omitempty"` + RowKeyStart *string `json:"startRk,omitempty"` + RowKeyEnd *string `json:"endRk,omitempty"` + KeyToSign *string `json:"keyToSign,omitempty"` + CacheControl *string `json:"rscc,omitempty"` + ContentDisposition *string `json:"rscd,omitempty"` + ContentEncoding *string `json:"rsce,omitempty"` + ContentLanguage *string `json:"rscl,omitempty"` + ContentType *string `json:"rsct,omitempty"` +} + // Sku is the SKU of the storage account. type Sku struct { Name SkuName `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/usage.go old mode 100644 new mode 100755 similarity index 60% rename from vendor/github.com/Azure/azure-sdk-for-go/arm/storage/usageoperations.go rename to vendor/github.com/Azure/azure-sdk-for-go/arm/storage/usage.go index 866efc9c311d..b12a6d315fda --- a/vendor/github.com/Azure/azure-sdk-for-go/arm/storage/usageoperations.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/arm/storage/usage.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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. @@ -24,53 +24,54 @@ import ( "net/http" ) -// UsageOperationsClient is the the Storage Management Client. -type UsageOperationsClient struct { +// UsageClient is the the Azure Storage Management API. +type UsageClient struct { ManagementClient } -// NewUsageOperationsClient creates an instance of the UsageOperationsClient -// client. -func NewUsageOperationsClient(subscriptionID string) UsageOperationsClient { - return NewUsageOperationsClientWithBaseURI(DefaultBaseURI, subscriptionID) +// NewUsageClient creates an instance of the UsageClient client. +func NewUsageClient(subscriptionID string) UsageClient { + return NewUsageClientWithBaseURI(DefaultBaseURI, subscriptionID) } -// NewUsageOperationsClientWithBaseURI creates an instance of the -// UsageOperationsClient client. -func NewUsageOperationsClientWithBaseURI(baseURI string, subscriptionID string) UsageOperationsClient { - return UsageOperationsClient{NewWithBaseURI(baseURI, subscriptionID)} +// NewUsageClientWithBaseURI creates an instance of the UsageClient client. +func NewUsageClientWithBaseURI(baseURI string, subscriptionID string) UsageClient { + return UsageClient{NewWithBaseURI(baseURI, subscriptionID)} } // List gets the current usage count and the limit for the resources under the // subscription. -func (client UsageOperationsClient) List() (result UsageListResult, err error) { +func (client UsageClient) List() (result UsageListResult, err error) { req, err := client.ListPreparer() if err != nil { - return result, autorest.NewErrorWithError(err, "storage.UsageOperationsClient", "List", nil, "Failure preparing request") + err = autorest.NewErrorWithError(err, "storage.UsageClient", "List", nil, "Failure preparing request") + return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "storage.UsageOperationsClient", "List", resp, "Failure sending request") + err = autorest.NewErrorWithError(err, "storage.UsageClient", "List", resp, "Failure sending request") + return } result, err = client.ListResponder(resp) if err != nil { - err = autorest.NewErrorWithError(err, "storage.UsageOperationsClient", "List", resp, "Failure responding to request") + err = autorest.NewErrorWithError(err, "storage.UsageClient", "List", resp, "Failure responding to request") } return } // ListPreparer prepares the List request. -func (client UsageOperationsClient) ListPreparer() (*http.Request, error) { +func (client UsageClient) ListPreparer() (*http.Request, error) { pathParameters := map[string]interface{}{ "subscriptionId": autorest.Encode("path", client.SubscriptionID), } + const APIVersion = "2016-12-01" queryParameters := map[string]interface{}{ - "api-version": client.APIVersion, + "api-version": APIVersion, } preparer := autorest.CreatePreparer( @@ -83,13 +84,13 @@ 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) { +func (client UsageClient) ListSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req) } // ListResponder handles the response to the List request. The method always // closes the http.Response Body. -func (client UsageOperationsClient) ListResponder(resp *http.Response) (result UsageListResult, err error) { +func (client UsageClient) ListResponder(resp *http.Response) (result UsageListResult, err error) { err = autorest.Respond( resp, client.ByInspecting(), 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 old mode 100644 new mode 100755 index e0a181c11a56..ac97c159fa6d --- 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,30 +14,16 @@ 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.17.0.0 +// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. -import ( - "fmt" -) - -const ( - major = "7" - minor = "0" - 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 arm-%s/%s" -) - // UserAgent returns the UserAgent string to use when sending http.Requests. func UserAgent() string { - return fmt.Sprintf(userAgentFormat, Version(), "storage", "2016-01-01") + return "Azure-SDK-For-Go/v10.0.2-beta arm-storage/2016-12-01" } // Version returns the semantic version (see http://semver.org) of the client. func Version() string { - return fmt.Sprintf(semVerFormat, major, minor, patch, tag) + return "v10.0.2-beta" } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/BUILD b/vendor/github.com/Azure/azure-sdk-for-go/storage/BUILD index f82f361022d8..4727d1d04ff0 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/storage/BUILD +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/BUILD @@ -10,15 +10,40 @@ load( go_library( name = "go_default_library", srcs = [ + "appendblob.go", + "authorization.go", "blob.go", + "blobsasuri.go", + "blobserviceclient.go", + "blockblob.go", "client.go", + "container.go", + "copyblob.go", + "directory.go", + "entity.go", "file.go", + "fileserviceclient.go", + "leaseblob.go", + "message.go", + "odata.go", + "pageblob.go", "queue.go", + "queueserviceclient.go", + "share.go", + "storagepolicy.go", + "storageservice.go", "table.go", - "table_entities.go", + "table_batch.go", + "tableserviceclient.go", "util.go", + "version.go", ], tags = ["automanaged"], + deps = [ + "//vendor/github.com/Azure/go-autorest/autorest:go_default_library", + "//vendor/github.com/Azure/go-autorest/autorest/azure:go_default_library", + "//vendor/github.com/satori/uuid:go_default_library", + ], ) filegroup( diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/README.md b/vendor/github.com/Azure/azure-sdk-for-go/storage/README.md deleted file mode 100644 index 0ab099848bba..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/storage/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# Azure Storage SDK for Go - -The `github.com/Azure/azure-sdk-for-go/storage` package is used to perform operations in Azure Storage Service. To manage your storage accounts (Azure Resource Manager / ARM), use the [github.com/Azure/azure-sdk-for-go/arm/storage](../arm/storage) package. For your classic storage accounts (Azure Service Management / ASM), use [github.com/Azure/azure-sdk-for-go/management/storageservice](../management/storageservice) package. - -This package includes support for [Azure Storage Emulator](https://azure.microsoft.com/documentation/articles/storage-use-emulator/) \ No newline at end of file diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/appendblob.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/appendblob.go new file mode 100644 index 000000000000..3292cb556951 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/appendblob.go @@ -0,0 +1,70 @@ +package storage + +import ( + "bytes" + "fmt" + "net/http" + "net/url" + "time" +) + +// PutAppendBlob initializes an empty append blob with specified name. An +// append blob must be created using this method before appending blocks. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Put-Blob +func (b *Blob) PutAppendBlob(options *PutBlobOptions) error { + params := url.Values{} + headers := b.Container.bsc.client.getStandardHeaders() + headers["x-ms-blob-type"] = string(BlobTypeAppend) + headers = mergeHeaders(headers, headersFromStruct(b.Properties)) + headers = b.Container.bsc.client.addMetadataToHeaders(headers, b.Metadata) + + if options != nil { + params = addTimeout(params, options.Timeout) + headers = mergeHeaders(headers, headersFromStruct(*options)) + } + uri := b.Container.bsc.client.getEndpoint(blobServiceName, b.buildPath(), params) + + resp, err := b.Container.bsc.client.exec(http.MethodPut, uri, headers, nil, b.Container.bsc.auth) + if err != nil { + return err + } + readAndCloseBody(resp.body) + return checkRespCode(resp.statusCode, []int{http.StatusCreated}) +} + +// AppendBlockOptions includes the options for an append block operation +type AppendBlockOptions struct { + Timeout uint + LeaseID string `header:"x-ms-lease-id"` + MaxSize *uint `header:"x-ms-blob-condition-maxsize"` + AppendPosition *uint `header:"x-ms-blob-condition-appendpos"` + IfModifiedSince *time.Time `header:"If-Modified-Since"` + IfUnmodifiedSince *time.Time `header:"If-Unmodified-Since"` + IfMatch string `header:"If-Match"` + IfNoneMatch string `header:"If-None-Match"` + RequestID string `header:"x-ms-client-request-id"` +} + +// AppendBlock appends a block to an append blob. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Append-Block +func (b *Blob) AppendBlock(chunk []byte, options *AppendBlockOptions) error { + params := url.Values{"comp": {"appendblock"}} + headers := b.Container.bsc.client.getStandardHeaders() + headers["x-ms-blob-type"] = string(BlobTypeAppend) + headers["Content-Length"] = fmt.Sprintf("%v", len(chunk)) + + if options != nil { + params = addTimeout(params, options.Timeout) + headers = mergeHeaders(headers, headersFromStruct(*options)) + } + uri := b.Container.bsc.client.getEndpoint(blobServiceName, b.buildPath(), params) + + resp, err := b.Container.bsc.client.exec(http.MethodPut, uri, headers, bytes.NewReader(chunk), b.Container.bsc.auth) + if err != nil { + return err + } + readAndCloseBody(resp.body) + return checkRespCode(resp.statusCode, []int{http.StatusCreated}) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/authorization.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/authorization.go new file mode 100644 index 000000000000..608bf3133866 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/authorization.go @@ -0,0 +1,227 @@ +// Package storage provides clients for Microsoft Azure Storage Services. +package storage + +import ( + "bytes" + "fmt" + "net/url" + "sort" + "strings" +) + +// See: https://docs.microsoft.com/rest/api/storageservices/fileservices/authentication-for-the-azure-storage-services + +type authentication string + +const ( + sharedKey authentication = "sharedKey" + sharedKeyForTable authentication = "sharedKeyTable" + sharedKeyLite authentication = "sharedKeyLite" + sharedKeyLiteForTable authentication = "sharedKeyLiteTable" + + // headers + headerAcceptCharset = "Accept-Charset" + headerAuthorization = "Authorization" + headerContentLength = "Content-Length" + headerDate = "Date" + headerXmsDate = "x-ms-date" + headerXmsVersion = "x-ms-version" + headerContentEncoding = "Content-Encoding" + headerContentLanguage = "Content-Language" + headerContentType = "Content-Type" + headerContentMD5 = "Content-MD5" + headerIfModifiedSince = "If-Modified-Since" + headerIfMatch = "If-Match" + headerIfNoneMatch = "If-None-Match" + headerIfUnmodifiedSince = "If-Unmodified-Since" + headerRange = "Range" + headerDataServiceVersion = "DataServiceVersion" + headerMaxDataServiceVersion = "MaxDataServiceVersion" + headerContentTransferEncoding = "Content-Transfer-Encoding" +) + +func (c *Client) addAuthorizationHeader(verb, url string, headers map[string]string, auth authentication) (map[string]string, error) { + authHeader, err := c.getSharedKey(verb, url, headers, auth) + if err != nil { + return nil, err + } + headers[headerAuthorization] = authHeader + return headers, nil +} + +func (c *Client) getSharedKey(verb, url string, headers map[string]string, auth authentication) (string, error) { + canRes, err := c.buildCanonicalizedResource(url, auth) + if err != nil { + return "", err + } + + canString, err := buildCanonicalizedString(verb, headers, canRes, auth) + if err != nil { + return "", err + } + return c.createAuthorizationHeader(canString, auth), nil +} + +func (c *Client) buildCanonicalizedResource(uri string, auth authentication) (string, error) { + errMsg := "buildCanonicalizedResource error: %s" + u, err := url.Parse(uri) + if err != nil { + return "", fmt.Errorf(errMsg, err.Error()) + } + + cr := bytes.NewBufferString("/") + cr.WriteString(c.getCanonicalizedAccountName()) + + if len(u.Path) > 0 { + // Any portion of the CanonicalizedResource string that is derived from + // the resource's URI should be encoded exactly as it is in the URI. + // -- https://msdn.microsoft.com/en-gb/library/azure/dd179428.aspx + cr.WriteString(u.EscapedPath()) + } + + params, err := url.ParseQuery(u.RawQuery) + if err != nil { + return "", fmt.Errorf(errMsg, err.Error()) + } + + // See https://github.com/Azure/azure-storage-net/blob/master/Lib/Common/Core/Util/AuthenticationUtility.cs#L277 + if auth == sharedKey { + if len(params) > 0 { + cr.WriteString("\n") + + keys := []string{} + for key := range params { + keys = append(keys, key) + } + sort.Strings(keys) + + completeParams := []string{} + for _, key := range keys { + if len(params[key]) > 1 { + sort.Strings(params[key]) + } + + completeParams = append(completeParams, fmt.Sprintf("%s:%s", key, strings.Join(params[key], ","))) + } + cr.WriteString(strings.Join(completeParams, "\n")) + } + } else { + // search for "comp" parameter, if exists then add it to canonicalizedresource + if v, ok := params["comp"]; ok { + cr.WriteString("?comp=" + v[0]) + } + } + + return string(cr.Bytes()), nil +} + +func (c *Client) getCanonicalizedAccountName() string { + // since we may be trying to access a secondary storage account, we need to + // remove the -secondary part of the storage name + return strings.TrimSuffix(c.accountName, "-secondary") +} + +func buildCanonicalizedString(verb string, headers map[string]string, canonicalizedResource string, auth authentication) (string, error) { + contentLength := headers[headerContentLength] + if contentLength == "0" { + contentLength = "" + } + date := headers[headerDate] + if v, ok := headers[headerXmsDate]; ok { + if auth == sharedKey || auth == sharedKeyLite { + date = "" + } else { + date = v + } + } + var canString string + switch auth { + case sharedKey: + canString = strings.Join([]string{ + verb, + headers[headerContentEncoding], + headers[headerContentLanguage], + contentLength, + headers[headerContentMD5], + headers[headerContentType], + date, + headers[headerIfModifiedSince], + headers[headerIfMatch], + headers[headerIfNoneMatch], + headers[headerIfUnmodifiedSince], + headers[headerRange], + buildCanonicalizedHeader(headers), + canonicalizedResource, + }, "\n") + case sharedKeyForTable: + canString = strings.Join([]string{ + verb, + headers[headerContentMD5], + headers[headerContentType], + date, + canonicalizedResource, + }, "\n") + case sharedKeyLite: + canString = strings.Join([]string{ + verb, + headers[headerContentMD5], + headers[headerContentType], + date, + buildCanonicalizedHeader(headers), + canonicalizedResource, + }, "\n") + case sharedKeyLiteForTable: + canString = strings.Join([]string{ + date, + canonicalizedResource, + }, "\n") + default: + return "", fmt.Errorf("%s authentication is not supported yet", auth) + } + return canString, nil +} + +func buildCanonicalizedHeader(headers map[string]string) string { + cm := make(map[string]string) + + for k, v := range headers { + headerName := strings.TrimSpace(strings.ToLower(k)) + if strings.HasPrefix(headerName, "x-ms-") { + cm[headerName] = v + } + } + + if len(cm) == 0 { + return "" + } + + keys := []string{} + for key := range cm { + keys = append(keys, key) + } + + sort.Strings(keys) + + ch := bytes.NewBufferString("") + + for _, key := range keys { + ch.WriteString(key) + ch.WriteRune(':') + ch.WriteString(cm[key]) + ch.WriteRune('\n') + } + + return strings.TrimSuffix(string(ch.Bytes()), "\n") +} + +func (c *Client) createAuthorizationHeader(canonicalizedString string, auth authentication) string { + signature := c.computeHmac256(canonicalizedString) + var key string + switch auth { + case sharedKey, sharedKeyForTable: + key = "SharedKey" + case sharedKeyLite, sharedKeyLiteForTable: + key = "SharedKeyLite" + } + return fmt.Sprintf("%s %s:%s", key, c.getCanonicalizedAccountName(), signature) +} 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 3dbaca52ade2..dd9eb386cb5a 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 @@ -1,12 +1,10 @@ package storage import ( - "bytes" "encoding/xml" "errors" "fmt" "io" - "io/ioutil" "net/http" "net/url" "strconv" @@ -14,51 +12,28 @@ import ( "time" ) -// BlobStorageClient contains operations for Microsoft Azure Blob Storage -// Service. -type BlobStorageClient struct { - client Client -} - -// A Container is an entry in ContainerListResponse. -type Container struct { - Name string `xml:"Name"` - Properties ContainerProperties `xml:"Properties"` - // TODO (ahmetalpbalkan) Metadata -} - -// ContainerProperties contains various properties of a container returned from -// various endpoints like ListContainers. -type ContainerProperties struct { - LastModified string `xml:"Last-Modified"` - Etag string `xml:"Etag"` - LeaseStatus string `xml:"LeaseStatus"` - LeaseState string `xml:"LeaseState"` - LeaseDuration string `xml:"LeaseDuration"` - // TODO (ahmetalpbalkan) remaining fields -} - -// ContainerListResponse contains the response fields from -// ListContainers call. -// -// See https://msdn.microsoft.com/en-us/library/azure/dd179352.aspx -type ContainerListResponse struct { - XMLName xml.Name `xml:"EnumerationResults"` - Xmlns string `xml:"xmlns,attr"` - Prefix string `xml:"Prefix"` - Marker string `xml:"Marker"` - NextMarker string `xml:"NextMarker"` - MaxResults int64 `xml:"MaxResults"` - Containers []Container `xml:"Containers>Container"` -} - // A Blob is an entry in BlobListResponse. type Blob struct { + Container *Container Name string `xml:"Name"` + Snapshot time.Time `xml:"Snapshot"` Properties BlobProperties `xml:"Properties"` Metadata BlobMetadata `xml:"Metadata"` } +// PutBlobOptions includes the options any put blob operation +// (page, block, append) +type PutBlobOptions struct { + Timeout uint + LeaseID string `header:"x-ms-lease-id"` + Origin string `header:"Origin"` + IfModifiedSince *time.Time `header:"If-Modified-Since"` + IfUnmodifiedSince *time.Time `header:"If-Unmodified-Since"` + IfMatch string `header:"If-Match"` + IfNoneMatch string `header:"If-None-Match"` + RequestID string `header:"x-ms-client-request-id"` +} + // BlobMetadata is a set of custom name/value pairs. // // See https://msdn.microsoft.com/en-us/library/azure/dd179404.aspx @@ -106,128 +81,28 @@ func (bm BlobMetadata) MarshalXML(enc *xml.Encoder, start xml.StartElement) erro // BlobProperties contains various properties of a blob // returned in various endpoints like ListBlobs or GetBlobProperties. type BlobProperties struct { - LastModified string `xml:"Last-Modified"` - Etag string `xml:"Etag"` - ContentMD5 string `xml:"Content-MD5"` - ContentLength int64 `xml:"Content-Length"` - ContentType string `xml:"Content-Type"` - ContentEncoding string `xml:"Content-Encoding"` - CacheControl string `xml:"Cache-Control"` - ContentLanguage string `xml:"Cache-Language"` - BlobType BlobType `xml:"x-ms-blob-blob-type"` - SequenceNumber int64 `xml:"x-ms-blob-sequence-number"` - CopyID string `xml:"CopyId"` - CopyStatus string `xml:"CopyStatus"` - CopySource string `xml:"CopySource"` - CopyProgress string `xml:"CopyProgress"` - CopyCompletionTime string `xml:"CopyCompletionTime"` - CopyStatusDescription string `xml:"CopyStatusDescription"` - LeaseStatus string `xml:"LeaseStatus"` -} - -// BlobHeaders contains various properties of a blob and is an entry -// in SetBlobProperties -type BlobHeaders struct { - ContentMD5 string `header:"x-ms-blob-content-md5"` - ContentLanguage string `header:"x-ms-blob-content-language"` - ContentEncoding string `header:"x-ms-blob-content-encoding"` - ContentType string `header:"x-ms-blob-content-type"` - CacheControl string `header:"x-ms-blob-cache-control"` -} - -// BlobListResponse contains the response fields from ListBlobs call. -// -// See https://msdn.microsoft.com/en-us/library/azure/dd135734.aspx -type BlobListResponse struct { - XMLName xml.Name `xml:"EnumerationResults"` - Xmlns string `xml:"xmlns,attr"` - Prefix string `xml:"Prefix"` - Marker string `xml:"Marker"` - 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 -// List Containers call. -// -// See https://msdn.microsoft.com/en-us/library/azure/dd179352.aspx -type ListContainersParameters struct { - Prefix string - Marker string - Include string - MaxResults uint - Timeout uint -} - -func (p ListContainersParameters) getParameters() url.Values { - out := url.Values{} - - if p.Prefix != "" { - out.Set("prefix", p.Prefix) - } - if p.Marker != "" { - out.Set("marker", p.Marker) - } - if p.Include != "" { - out.Set("include", p.Include) - } - if p.MaxResults != 0 { - out.Set("maxresults", fmt.Sprintf("%v", p.MaxResults)) - } - if p.Timeout != 0 { - out.Set("timeout", fmt.Sprintf("%v", p.Timeout)) - } - - return out -} - -// ListBlobsParameters defines the set of customizable -// parameters to make a List Blobs call. -// -// See https://msdn.microsoft.com/en-us/library/azure/dd135734.aspx -type ListBlobsParameters struct { - Prefix string - Delimiter string - Marker string - Include string - MaxResults uint - Timeout uint -} - -func (p ListBlobsParameters) getParameters() url.Values { - out := url.Values{} - - if p.Prefix != "" { - out.Set("prefix", p.Prefix) - } - if p.Delimiter != "" { - out.Set("delimiter", p.Delimiter) - } - if p.Marker != "" { - out.Set("marker", p.Marker) - } - if p.Include != "" { - out.Set("include", p.Include) - } - if p.MaxResults != 0 { - out.Set("maxresults", fmt.Sprintf("%v", p.MaxResults)) - } - if p.Timeout != 0 { - out.Set("timeout", fmt.Sprintf("%v", p.Timeout)) - } - - return out + LastModified TimeRFC1123 `xml:"Last-Modified"` + Etag string `xml:"Etag"` + ContentMD5 string `xml:"Content-MD5" header:"x-ms-blob-content-md5"` + ContentLength int64 `xml:"Content-Length"` + ContentType string `xml:"Content-Type" header:"x-ms-blob-content-type"` + ContentEncoding string `xml:"Content-Encoding" header:"x-ms-blob-content-encoding"` + CacheControl string `xml:"Cache-Control" header:"x-ms-blob-cache-control"` + ContentLanguage string `xml:"Cache-Language" header:"x-ms-blob-content-language"` + ContentDisposition string `xml:"Content-Disposition" header:"x-ms-blob-content-disposition"` + BlobType BlobType `xml:"x-ms-blob-blob-type"` + SequenceNumber int64 `xml:"x-ms-blob-sequence-number"` + CopyID string `xml:"CopyId"` + CopyStatus string `xml:"CopyStatus"` + CopySource string `xml:"CopySource"` + CopyProgress string `xml:"CopyProgress"` + CopyCompletionTime TimeRFC1123 `xml:"CopyCompletionTime"` + CopyStatusDescription string `xml:"CopyStatusDescription"` + LeaseStatus string `xml:"LeaseStatus"` + LeaseState string `xml:"LeaseState"` + LeaseDuration string `xml:"LeaseDuration"` + ServerEncrypted bool `xml:"ServerEncrypted"` + IncrementalCopy bool `xml:"IncrementalCopy"` } // BlobType defines the type of the Azure Blob. @@ -240,257 +115,18 @@ const ( BlobTypeAppend BlobType = "AppendBlob" ) -// PageWriteType defines the type updates that are going to be -// done on the page blob. -type PageWriteType string - -// Types of operations on page blobs -const ( - PageWriteTypeUpdate PageWriteType = "update" - PageWriteTypeClear PageWriteType = "clear" -) - -const ( - blobCopyStatusPending = "pending" - blobCopyStatusSuccess = "success" - blobCopyStatusAborted = "aborted" - blobCopyStatusFailed = "failed" -) - -// lease constants. -const ( - leaseHeaderPrefix = "x-ms-lease-" - leaseID = "x-ms-lease-id" - leaseAction = "x-ms-lease-action" - leaseBreakPeriod = "x-ms-lease-break-period" - leaseDuration = "x-ms-lease-duration" - leaseProposedID = "x-ms-proposed-lease-id" - leaseTime = "x-ms-lease-time" - - acquireLease = "acquire" - renewLease = "renew" - changeLease = "change" - releaseLease = "release" - breakLease = "break" -) - -// BlockListType is used to filter out types of blocks in a Get Blocks List call -// for a block blob. -// -// See https://msdn.microsoft.com/en-us/library/azure/dd179400.aspx for all -// block types. -type BlockListType string - -// Filters for listing blocks in block blobs -const ( - BlockListTypeAll BlockListType = "all" - BlockListTypeCommitted BlockListType = "committed" - BlockListTypeUncommitted BlockListType = "uncommitted" -) - -// ContainerAccessType defines the access level to the container from a public -// request. -// -// See https://msdn.microsoft.com/en-us/library/azure/dd179468.aspx and "x-ms- -// blob-public-access" header. -type ContainerAccessType string - -// Access options for containers -const ( - ContainerAccessTypePrivate ContainerAccessType = "" - ContainerAccessTypeBlob ContainerAccessType = "blob" - ContainerAccessTypeContainer ContainerAccessType = "container" -) - -// ContainerAccessOptions are used when setting ACLs of containers (after creation) -type ContainerAccessOptions struct { - ContainerAccess ContainerAccessType - Timeout int - LeaseID string -} - -// AccessPolicyDetails are used for SETTING policies -type AccessPolicyDetails struct { - ID string - StartTime time.Time - ExpiryTime time.Time - CanRead bool - CanWrite bool - CanDelete bool -} - -// ContainerPermissions is used when setting permissions and Access Policies for containers. -type ContainerPermissions struct { - AccessOptions ContainerAccessOptions - AccessPolicy AccessPolicyDetails -} - -// AccessPolicyDetailsXML has specifics about an access policy -// annotated with XML details. -type AccessPolicyDetailsXML struct { - StartTime time.Time `xml:"Start"` - ExpiryTime time.Time `xml:"Expiry"` - Permission string `xml:"Permission"` -} - -// SignedIdentifier is a wrapper for a specific policy -type SignedIdentifier struct { - ID string `xml:"Id"` - AccessPolicy AccessPolicyDetailsXML `xml:"AccessPolicy"` -} - -// SignedIdentifiers part of the response from GetPermissions call. -type SignedIdentifiers struct { - SignedIdentifiers []SignedIdentifier `xml:"SignedIdentifier"` -} - -// AccessPolicy is the response type from the GetPermissions call. -type AccessPolicy struct { - SignedIdentifiersList SignedIdentifiers `xml:"SignedIdentifiers"` -} - -// ContainerAccessResponse is returned for the GetContainerPermissions function. -// This contains both the permission and access policy for the container. -type ContainerAccessResponse struct { - ContainerAccess ContainerAccessType - AccessPolicy SignedIdentifiers -} - -// ContainerAccessHeader references header used when setting/getting container ACL -const ( - ContainerAccessHeader string = "x-ms-blob-public-access" -) - -// Maximum sizes (per REST API) for various concepts -const ( - MaxBlobBlockSize = 4 * 1024 * 1024 - MaxBlobPageSize = 4 * 1024 * 1024 -) - -// BlockStatus defines states a block for a block blob can -// be in. -type BlockStatus string - -// List of statuses that can be used to refer to a block in a block list -const ( - BlockStatusUncommitted BlockStatus = "Uncommitted" - BlockStatusCommitted BlockStatus = "Committed" - BlockStatusLatest BlockStatus = "Latest" -) - -// Block is used to create Block entities for Put Block List -// call. -type Block struct { - ID string - Status BlockStatus -} - -// BlockListResponse contains the response fields from Get Block List call. -// -// See https://msdn.microsoft.com/en-us/library/azure/dd179400.aspx -type BlockListResponse struct { - XMLName xml.Name `xml:"BlockList"` - CommittedBlocks []BlockResponse `xml:"CommittedBlocks>Block"` - UncommittedBlocks []BlockResponse `xml:"UncommittedBlocks>Block"` -} - -// BlockResponse contains the block information returned -// in the GetBlockListCall. -type BlockResponse struct { - Name string `xml:"Name"` - Size int64 `xml:"Size"` -} - -// GetPageRangesResponse contains the reponse fields from -// Get Page Ranges call. -// -// See https://msdn.microsoft.com/en-us/library/azure/ee691973.aspx -type GetPageRangesResponse struct { - XMLName xml.Name `xml:"PageList"` - PageList []PageRange `xml:"PageRange"` -} - -// PageRange contains information about a page of a page blob from -// Get Pages Range call. -// -// See https://msdn.microsoft.com/en-us/library/azure/ee691973.aspx -type PageRange struct { - Start int64 `xml:"Start"` - End int64 `xml:"End"` -} - -var ( - errBlobCopyAborted = errors.New("storage: blob copy is aborted") - errBlobCopyIDMismatch = errors.New("storage: blob copy id is a mismatch") -) - -// ListContainers returns the list of containers in a storage account along with -// pagination token and other response details. -// -// See https://msdn.microsoft.com/en-us/library/azure/dd179352.aspx -func (b BlobStorageClient) ListContainers(params ListContainersParameters) (ContainerListResponse, error) { - q := mergeParams(params.getParameters(), url.Values{"comp": {"list"}}) - uri := b.client.getEndpoint(blobServiceName, "", q) - headers := b.client.getStandardHeaders() - - var out ContainerListResponse - resp, err := b.client.exec("GET", uri, headers, nil) - if err != nil { - return out, err - } - defer resp.body.Close() - - err = xmlUnmarshal(resp.body, &out) - return out, err -} - -// CreateContainer creates a blob container within the storage account -// with given name and access level. Returns error if container already exists. -// -// See https://msdn.microsoft.com/en-us/library/azure/dd179468.aspx -func (b BlobStorageClient) CreateContainer(name string, access ContainerAccessType) error { - resp, err := b.createContainer(name, access) - if err != nil { - return err - } - defer resp.body.Close() - return checkRespCode(resp.statusCode, []int{http.StatusCreated}) -} - -// CreateContainerIfNotExists creates a blob container if it does not exist. Returns -// true if container is newly created or false if container already exists. -func (b BlobStorageClient) CreateContainerIfNotExists(name string, access ContainerAccessType) (bool, error) { - resp, err := b.createContainer(name, access) - if resp != nil { - defer resp.body.Close() - if resp.statusCode == http.StatusCreated || resp.statusCode == http.StatusConflict { - return resp.statusCode == http.StatusCreated, nil - } - } - return false, err -} - -func (b BlobStorageClient) createContainer(name string, access ContainerAccessType) (*storageResponse, error) { - verb := "PUT" - uri := b.client.getEndpoint(blobServiceName, pathForContainer(name), url.Values{"restype": {"container"}}) - - headers := b.client.getStandardHeaders() - if access != "" { - headers[ContainerAccessHeader] = string(access) - } - return b.client.exec(verb, uri, headers, nil) +func (b *Blob) buildPath() string { + return b.Container.buildPath() + "/" + b.Name } -// ContainerExists returns true if a container with given name exists -// on the storage account, otherwise returns false. -func (b BlobStorageClient) ContainerExists(name string) (bool, error) { - verb := "HEAD" - uri := b.client.getEndpoint(blobServiceName, pathForContainer(name), url.Values{"restype": {"container"}}) - headers := b.client.getStandardHeaders() - - resp, err := b.client.exec(verb, uri, headers, nil) +// Exists returns true if a blob with given name exists on the specified +// container of the storage account. +func (b *Blob) Exists() (bool, error) { + uri := b.Container.bsc.client.getEndpoint(blobServiceName, b.buildPath(), nil) + headers := b.Container.bsc.client.getStandardHeaders() + resp, err := b.Container.bsc.client.exec(http.MethodHead, uri, headers, nil, b.Container.bsc.auth) if resp != nil { - defer resp.body.Close() + defer readAndCloseBody(resp.body) if resp.statusCode == http.StatusOK || resp.statusCode == http.StatusNotFound { return resp.statusCode == http.StatusOK, nil } @@ -498,194 +134,57 @@ func (b BlobStorageClient) ContainerExists(name string) (bool, error) { return false, err } -// SetContainerPermissions sets up container permissions as per https://msdn.microsoft.com/en-us/library/azure/dd179391.aspx -func (b BlobStorageClient) SetContainerPermissions(container string, containerPermissions ContainerPermissions) (err error) { - params := url.Values{ - "restype": {"container"}, - "comp": {"acl"}, - } - - if containerPermissions.AccessOptions.Timeout > 0 { - params.Add("timeout", strconv.Itoa(containerPermissions.AccessOptions.Timeout)) - } - - uri := b.client.getEndpoint(blobServiceName, pathForContainer(container), params) - headers := b.client.getStandardHeaders() - if containerPermissions.AccessOptions.ContainerAccess != "" { - headers[ContainerAccessHeader] = string(containerPermissions.AccessOptions.ContainerAccess) - } - - if containerPermissions.AccessOptions.LeaseID != "" { - headers[leaseID] = containerPermissions.AccessOptions.LeaseID - } - - // generate the XML for the SharedAccessSignature if required. - accessPolicyXML, err := generateAccessPolicy(containerPermissions.AccessPolicy) - if err != nil { - return err - } - - var resp *storageResponse - if accessPolicyXML != "" { - headers["Content-Length"] = strconv.Itoa(len(accessPolicyXML)) - resp, err = b.client.exec("PUT", uri, headers, strings.NewReader(accessPolicyXML)) - } else { - resp, err = b.client.exec("PUT", uri, headers, nil) - } - - if err != nil { - return err - } - - if resp != nil { - defer func() { - err = resp.body.Close() - }() - - if resp.statusCode != http.StatusOK { - return errors.New("Unable to set permissions") - } +// GetURL gets the canonical URL to the blob with the specified name in the +// specified container. If name is not specified, the canonical URL for the entire +// container is obtained. +// This method does not create a publicly accessible URL if the blob or container +// is private and this method does not check if the blob exists. +func (b *Blob) GetURL() string { + container := b.Container.Name + if container == "" { + container = "$root" } - return nil + return b.Container.bsc.client.getEndpoint(blobServiceName, pathForResource(container, b.Name), nil) } -// GetContainerPermissions gets the container permissions as per https://msdn.microsoft.com/en-us/library/azure/dd179469.aspx -// If timeout is 0 then it will not be passed to Azure -// leaseID will only be passed to Azure if populated -// Returns permissionResponse which is combined permissions and AccessPolicy -func (b BlobStorageClient) GetContainerPermissions(container string, timeout int, leaseID string) (permissionResponse *ContainerAccessResponse, err error) { - params := url.Values{"restype": {"container"}, - "comp": {"acl"}} - - if timeout > 0 { - params.Add("timeout", strconv.Itoa(timeout)) - } - - uri := b.client.getEndpoint(blobServiceName, pathForContainer(container), params) - headers := b.client.getStandardHeaders() - - if leaseID != "" { - headers[leaseID] = leaseID - } - - resp, err := b.client.exec("GET", uri, headers, nil) - if err != nil { - return nil, err - } - - // containerAccess. Blob, Container, empty - containerAccess := resp.headers.Get(http.CanonicalHeaderKey(ContainerAccessHeader)) - - defer func() { - err = resp.body.Close() - }() - - var out AccessPolicy - err = xmlUnmarshal(resp.body, &out.SignedIdentifiersList) - if err != nil { - return nil, err - } - - permissionResponse = &ContainerAccessResponse{} - permissionResponse.AccessPolicy = out.SignedIdentifiersList - permissionResponse.ContainerAccess = ContainerAccessType(containerAccess) - - return permissionResponse, nil +// GetBlobRangeOptions includes the options for a get blob range operation +type GetBlobRangeOptions struct { + Range *BlobRange + GetRangeContentMD5 bool + *GetBlobOptions } -// DeleteContainer deletes the container with given name on the storage -// account. If the container does not exist returns error. -// -// See https://msdn.microsoft.com/en-us/library/azure/dd179408.aspx -func (b BlobStorageClient) DeleteContainer(name string) error { - resp, err := b.deleteContainer(name) - if err != nil { - return err - } - defer resp.body.Close() - return checkRespCode(resp.statusCode, []int{http.StatusAccepted}) +// GetBlobOptions includes the options for a get blob operation +type GetBlobOptions struct { + Timeout uint + Snapshot *time.Time + LeaseID string `header:"x-ms-lease-id"` + Origin string `header:"Origin"` + IfModifiedSince *time.Time `header:"If-Modified-Since"` + IfUnmodifiedSince *time.Time `header:"If-Unmodified-Since"` + IfMatch string `header:"If-Match"` + IfNoneMatch string `header:"If-None-Match"` + RequestID string `header:"x-ms-client-request-id"` } -// DeleteContainerIfExists deletes the container with given name on the storage -// account if it exists. Returns true if container is deleted with this call, or -// false if the container did not exist at the time of the Delete Container -// operation. -// -// See https://msdn.microsoft.com/en-us/library/azure/dd179408.aspx -func (b BlobStorageClient) DeleteContainerIfExists(name string) (bool, error) { - resp, err := b.deleteContainer(name) - if resp != nil { - defer resp.body.Close() - if resp.statusCode == http.StatusAccepted || resp.statusCode == http.StatusNotFound { - return resp.statusCode == http.StatusAccepted, nil - } - } - return false, err +// BlobRange represents the bytes range to be get +type BlobRange struct { + Start uint64 + End uint64 } -func (b BlobStorageClient) deleteContainer(name string) (*storageResponse, error) { - verb := "DELETE" - uri := b.client.getEndpoint(blobServiceName, pathForContainer(name), url.Values{"restype": {"container"}}) - - headers := b.client.getStandardHeaders() - return b.client.exec(verb, uri, headers, nil) +func (br BlobRange) String() string { + return fmt.Sprintf("bytes=%d-%d", br.Start, br.End) } -// ListBlobs returns an object that contains list of blobs in the container, -// pagination token and other information in the response of List Blobs call. -// -// See https://msdn.microsoft.com/en-us/library/azure/dd135734.aspx -func (b BlobStorageClient) ListBlobs(container string, params ListBlobsParameters) (BlobListResponse, error) { - q := mergeParams(params.getParameters(), url.Values{ - "restype": {"container"}, - "comp": {"list"}}) - uri := b.client.getEndpoint(blobServiceName, pathForContainer(container), q) - headers := b.client.getStandardHeaders() - - var out BlobListResponse - resp, err := b.client.exec("GET", uri, headers, nil) - if err != nil { - return out, err +// Get returns a stream to read the blob. Caller must call both Read and Close() +// to correctly close the underlying connection. +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Get-Blob +func (b *Blob) Get(options *GetBlobOptions) (io.ReadCloser, error) { + rangeOptions := GetBlobRangeOptions{ + GetBlobOptions: options, } - defer resp.body.Close() - - err = xmlUnmarshal(resp.body, &out) - return out, err -} - -// BlobExists returns true if a blob with given name exists on the specified -// container of the storage account. -func (b BlobStorageClient) BlobExists(container, name string) (bool, error) { - verb := "HEAD" - uri := b.client.getEndpoint(blobServiceName, pathForBlob(container, name), url.Values{}) - headers := b.client.getStandardHeaders() - resp, err := b.client.exec(verb, uri, headers, nil) - if resp != nil { - defer resp.body.Close() - if resp.statusCode == http.StatusOK || resp.statusCode == http.StatusNotFound { - return resp.statusCode == http.StatusOK, nil - } - } - return false, err -} - -// GetBlobURL gets the canonical URL to the blob with the specified name in the -// specified container. This method does not create a publicly accessible URL if -// the blob or container is private and this method does not check if the blob -// exists. -func (b BlobStorageClient) GetBlobURL(container, name string) string { - if container == "" { - container = "$root" - } - return b.client.getEndpoint(blobServiceName, pathForBlob(container, name), url.Values{}) -} - -// GetBlob returns a stream to read the blob. Caller must call Close() the -// reader to close on the underlying connection. -// -// 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, "", nil) + resp, err := b.getRange(&rangeOptions) if err != nil { return nil, err } @@ -693,15 +192,19 @@ func (b BlobStorageClient) GetBlob(container, name string) (io.ReadCloser, error if err := checkRespCode(resp.statusCode, []int{http.StatusOK}); err != nil { return nil, err } + if err := b.writePropoerties(resp.headers); err != nil { + return resp.body, err + } return resp.body, nil } -// GetBlobRange reads the specified range of a blob to a stream. The bytesRange +// GetRange reads the specified range of a blob to a stream. The bytesRange // 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, extraHeaders map[string]string) (io.ReadCloser, error) { - resp, err := b.getBlobRange(container, name, bytesRange, extraHeaders) +// Caller must call both Read and Close()// to correctly close the underlying +// connection. +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Get-Blob +func (b *Blob) GetRange(options *GetBlobRangeOptions) (io.ReadCloser, error) { + resp, err := b.getRange(options) if err != nil { return nil, err } @@ -709,65 +212,65 @@ func (b BlobStorageClient) GetBlobRange(container, name, bytesRange string, extr if err := checkRespCode(resp.statusCode, []int{http.StatusPartialContent}); err != nil { return nil, err } + if err := b.writePropoerties(resp.headers); err != nil { + return resp.body, err + } return resp.body, nil } -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{}) - - headers := b.client.getStandardHeaders() - if bytesRange != "" { - headers["Range"] = fmt.Sprintf("bytes=%s", bytesRange) - } +func (b *Blob) getRange(options *GetBlobRangeOptions) (*storageResponse, error) { + params := url.Values{} + headers := b.Container.bsc.client.getStandardHeaders() - for k, v := range extraHeaders { - headers[k] = v + if options != nil { + if options.Range != nil { + headers["Range"] = options.Range.String() + headers["x-ms-range-get-content-md5"] = fmt.Sprintf("%v", options.GetRangeContentMD5) + } + if options.GetBlobOptions != nil { + headers = mergeHeaders(headers, headersFromStruct(*options.GetBlobOptions)) + params = addTimeout(params, options.Timeout) + params = addSnapshot(params, options.Snapshot) + } } + uri := b.Container.bsc.client.getEndpoint(blobServiceName, b.buildPath(), params) - resp, err := b.client.exec(verb, uri, headers, nil) + resp, err := b.Container.bsc.client.exec(http.MethodGet, uri, headers, nil, b.Container.bsc.auth) if err != nil { return nil, err } return resp, err } -// leasePut is common PUT code for the various aquire/release/break etc functions. -func (b BlobStorageClient) leaseCommonPut(container string, name string, headers map[string]string, expectedStatus int) (http.Header, error) { - params := url.Values{"comp": {"lease"}} - uri := b.client.getEndpoint(blobServiceName, pathForBlob(container, name), params) - - resp, err := b.client.exec("PUT", uri, headers, nil) - if err != nil { - return nil, err - } - defer resp.body.Close() - - if err := checkRespCode(resp.statusCode, []int{expectedStatus}); err != nil { - return nil, err - } - - return resp.headers, nil +// SnapshotOptions includes the options for a snapshot blob operation +type SnapshotOptions struct { + Timeout uint + LeaseID string `header:"x-ms-lease-id"` + IfModifiedSince *time.Time `header:"If-Modified-Since"` + IfUnmodifiedSince *time.Time `header:"If-Unmodified-Since"` + IfMatch string `header:"If-Match"` + IfNoneMatch string `header:"If-None-Match"` + RequestID string `header:"x-ms-client-request-id"` } -// SnapshotBlob creates a snapshot for a blob as per https://msdn.microsoft.com/en-us/library/azure/ee691971.aspx -func (b BlobStorageClient) SnapshotBlob(container string, name string, timeout int, extraHeaders map[string]string) (snapshotTimestamp *time.Time, err error) { - headers := b.client.getStandardHeaders() +// CreateSnapshot creates a snapshot for a blob +// See https://msdn.microsoft.com/en-us/library/azure/ee691971.aspx +func (b *Blob) CreateSnapshot(options *SnapshotOptions) (snapshotTimestamp *time.Time, err error) { params := url.Values{"comp": {"snapshot"}} + headers := b.Container.bsc.client.getStandardHeaders() + headers = b.Container.bsc.client.addMetadataToHeaders(headers, b.Metadata) - if timeout > 0 { - params.Add("timeout", strconv.Itoa(timeout)) + if options != nil { + params = addTimeout(params, options.Timeout) + headers = mergeHeaders(headers, headersFromStruct(*options)) } + uri := b.Container.bsc.client.getEndpoint(blobServiceName, b.buildPath(), params) - for k, v := range extraHeaders { - headers[k] = v - } - - uri := b.client.getEndpoint(blobServiceName, pathForBlob(container, name), params) - resp, err := b.client.exec("PUT", uri, headers, nil) - if err != nil { + resp, err := b.Container.bsc.client.exec(http.MethodPut, uri, headers, nil, b.Container.bsc.auth) + if err != nil || resp == nil { return nil, err } + defer readAndCloseBody(resp.body) if err := checkRespCode(resp.statusCode, []int{http.StatusCreated}); err != nil { return nil, err @@ -779,212 +282,178 @@ func (b BlobStorageClient) SnapshotBlob(container string, name string, timeout i if err != nil { return nil, err } - return &snapshotTimestamp, nil } return nil, errors.New("Snapshot not created") } -// AcquireLease creates a lease for a blob as per https://msdn.microsoft.com/en-us/library/azure/ee691972.aspx -// returns leaseID acquired -func (b BlobStorageClient) AcquireLease(container string, name string, leaseTimeInSeconds int, proposedLeaseID string) (returnedLeaseID string, err error) { - headers := b.client.getStandardHeaders() - headers[leaseAction] = acquireLease - - if leaseTimeInSeconds > 0 { - headers[leaseDuration] = strconv.Itoa(leaseTimeInSeconds) - } - - if proposedLeaseID != "" { - headers[leaseProposedID] = proposedLeaseID - } - - respHeaders, err := b.leaseCommonPut(container, name, headers, http.StatusCreated) - if err != nil { - return "", err - } - - returnedLeaseID = respHeaders.Get(http.CanonicalHeaderKey(leaseID)) - - if returnedLeaseID != "" { - return returnedLeaseID, nil - } - - return "", errors.New("LeaseID not returned") -} - -// BreakLease breaks the lease for a blob as per https://msdn.microsoft.com/en-us/library/azure/ee691972.aspx -// Returns the timeout remaining in the lease in seconds -func (b BlobStorageClient) BreakLease(container string, name string) (breakTimeout int, err error) { - headers := b.client.getStandardHeaders() - headers[leaseAction] = breakLease - return b.breakLeaseCommon(container, name, headers) -} - -// BreakLeaseWithBreakPeriod breaks the lease for a blob as per https://msdn.microsoft.com/en-us/library/azure/ee691972.aspx -// breakPeriodInSeconds is used to determine how long until new lease can be created. -// Returns the timeout remaining in the lease in seconds -func (b BlobStorageClient) BreakLeaseWithBreakPeriod(container string, name string, breakPeriodInSeconds int) (breakTimeout int, err error) { - headers := b.client.getStandardHeaders() - headers[leaseAction] = breakLease - headers[leaseBreakPeriod] = strconv.Itoa(breakPeriodInSeconds) - return b.breakLeaseCommon(container, name, headers) +// GetBlobPropertiesOptions includes the options for a get blob properties operation +type GetBlobPropertiesOptions struct { + Timeout uint + Snapshot *time.Time + LeaseID string `header:"x-ms-lease-id"` + IfModifiedSince *time.Time `header:"If-Modified-Since"` + IfUnmodifiedSince *time.Time `header:"If-Unmodified-Since"` + IfMatch string `header:"If-Match"` + IfNoneMatch string `header:"If-None-Match"` + RequestID string `header:"x-ms-client-request-id"` } -// breakLeaseCommon is common code for both version of BreakLease (with and without break period) -func (b BlobStorageClient) breakLeaseCommon(container string, name string, headers map[string]string) (breakTimeout int, err error) { +// GetProperties provides various information about the specified blob. +// See https://msdn.microsoft.com/en-us/library/azure/dd179394.aspx +func (b *Blob) GetProperties(options *GetBlobPropertiesOptions) error { + params := url.Values{} + headers := b.Container.bsc.client.getStandardHeaders() - respHeaders, err := b.leaseCommonPut(container, name, headers, http.StatusAccepted) - if err != nil { - return 0, err + if options != nil { + params = addTimeout(params, options.Timeout) + params = addSnapshot(params, options.Snapshot) + headers = mergeHeaders(headers, headersFromStruct(*options)) } + uri := b.Container.bsc.client.getEndpoint(blobServiceName, b.buildPath(), params) - breakTimeoutStr := respHeaders.Get(http.CanonicalHeaderKey(leaseTime)) - if breakTimeoutStr != "" { - breakTimeout, err = strconv.Atoi(breakTimeoutStr) - if err != nil { - return 0, err - } - } - - return breakTimeout, nil -} - -// ChangeLease changes a lease ID for a blob as per https://msdn.microsoft.com/en-us/library/azure/ee691972.aspx -// Returns the new LeaseID acquired -func (b BlobStorageClient) ChangeLease(container string, name string, currentLeaseID string, proposedLeaseID string) (newLeaseID string, err error) { - headers := b.client.getStandardHeaders() - headers[leaseAction] = changeLease - headers[leaseID] = currentLeaseID - headers[leaseProposedID] = proposedLeaseID - - respHeaders, err := b.leaseCommonPut(container, name, headers, http.StatusOK) - if err != nil { - return "", err - } - - newLeaseID = respHeaders.Get(http.CanonicalHeaderKey(leaseID)) - if newLeaseID != "" { - return newLeaseID, nil - } - - return "", errors.New("LeaseID not returned") -} - -// ReleaseLease releases the lease for a blob as per https://msdn.microsoft.com/en-us/library/azure/ee691972.aspx -func (b BlobStorageClient) ReleaseLease(container string, name string, currentLeaseID string) error { - headers := b.client.getStandardHeaders() - headers[leaseAction] = releaseLease - headers[leaseID] = currentLeaseID - - _, err := b.leaseCommonPut(container, name, headers, http.StatusOK) + resp, err := b.Container.bsc.client.exec(http.MethodHead, uri, headers, nil, b.Container.bsc.auth) if err != nil { return err } + defer readAndCloseBody(resp.body) - return nil -} - -// RenewLease renews the lease for a blob as per https://msdn.microsoft.com/en-us/library/azure/ee691972.aspx -func (b BlobStorageClient) RenewLease(container string, name string, currentLeaseID string) error { - headers := b.client.getStandardHeaders() - headers[leaseAction] = renewLease - headers[leaseID] = currentLeaseID - - _, err := b.leaseCommonPut(container, name, headers, http.StatusOK) - if err != nil { + if err = checkRespCode(resp.statusCode, []int{http.StatusOK}); err != nil { return err } - - return nil + return b.writePropoerties(resp.headers) } -// GetBlobProperties provides various information about the specified -// blob. See https://msdn.microsoft.com/en-us/library/azure/dd179394.aspx -func (b BlobStorageClient) GetBlobProperties(container, name string) (*BlobProperties, error) { - verb := "HEAD" - uri := b.client.getEndpoint(blobServiceName, pathForBlob(container, name), url.Values{}) - - headers := b.client.getStandardHeaders() - resp, err := b.client.exec(verb, 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 - } +func (b *Blob) writePropoerties(h http.Header) error { + var err error var contentLength int64 - contentLengthStr := resp.headers.Get("Content-Length") + contentLengthStr := h.Get("Content-Length") if contentLengthStr != "" { contentLength, err = strconv.ParseInt(contentLengthStr, 0, 64) if err != nil { - return nil, err + return err } } var sequenceNum int64 - sequenceNumStr := resp.headers.Get("x-ms-blob-sequence-number") + sequenceNumStr := h.Get("x-ms-blob-sequence-number") if sequenceNumStr != "" { sequenceNum, err = strconv.ParseInt(sequenceNumStr, 0, 64) if err != nil { - return nil, err + return err } } - return &BlobProperties{ - LastModified: resp.headers.Get("Last-Modified"), - Etag: resp.headers.Get("Etag"), - ContentMD5: resp.headers.Get("Content-MD5"), + lastModified, err := getTimeFromHeaders(h, "Last-Modified") + if err != nil { + return err + } + + copyCompletionTime, err := getTimeFromHeaders(h, "x-ms-copy-completion-time") + if err != nil { + return err + } + + b.Properties = BlobProperties{ + LastModified: TimeRFC1123(*lastModified), + Etag: h.Get("Etag"), + ContentMD5: h.Get("Content-MD5"), ContentLength: contentLength, - ContentEncoding: resp.headers.Get("Content-Encoding"), - ContentType: resp.headers.Get("Content-Type"), - CacheControl: resp.headers.Get("Cache-Control"), - ContentLanguage: resp.headers.Get("Content-Language"), + ContentEncoding: h.Get("Content-Encoding"), + ContentType: h.Get("Content-Type"), + ContentDisposition: h.Get("Content-Disposition"), + CacheControl: h.Get("Cache-Control"), + ContentLanguage: h.Get("Content-Language"), SequenceNumber: sequenceNum, - CopyCompletionTime: resp.headers.Get("x-ms-copy-completion-time"), - CopyStatusDescription: resp.headers.Get("x-ms-copy-status-description"), - CopyID: resp.headers.Get("x-ms-copy-id"), - CopyProgress: resp.headers.Get("x-ms-copy-progress"), - 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 + CopyCompletionTime: TimeRFC1123(*copyCompletionTime), + CopyStatusDescription: h.Get("x-ms-copy-status-description"), + CopyID: h.Get("x-ms-copy-id"), + CopyProgress: h.Get("x-ms-copy-progress"), + CopySource: h.Get("x-ms-copy-source"), + CopyStatus: h.Get("x-ms-copy-status"), + BlobType: BlobType(h.Get("x-ms-blob-type")), + LeaseStatus: h.Get("x-ms-lease-status"), + LeaseState: h.Get("x-ms-lease-state"), + } + b.writeMetadata(h) + return nil +} + +// SetBlobPropertiesOptions contains various properties of a blob and is an entry +// in SetProperties +type SetBlobPropertiesOptions struct { + Timeout uint + LeaseID string `header:"x-ms-lease-id"` + Origin string `header:"Origin"` + IfModifiedSince *time.Time `header:"If-Modified-Since"` + IfUnmodifiedSince *time.Time `header:"If-Unmodified-Since"` + IfMatch string `header:"If-Match"` + IfNoneMatch string `header:"If-None-Match"` + SequenceNumberAction *SequenceNumberAction + RequestID string `header:"x-ms-client-request-id"` } -// SetBlobProperties replaces the BlobHeaders for the specified blob. +// SequenceNumberAction defines how the blob's sequence number should be modified +type SequenceNumberAction string + +// Options for sequence number action +const ( + SequenceNumberActionMax SequenceNumberAction = "max" + SequenceNumberActionUpdate SequenceNumberAction = "update" + SequenceNumberActionIncrement SequenceNumberAction = "increment" +) + +// SetProperties replaces the BlobHeaders for the specified blob. // // Some keys may be converted to Camel-Case before sending. All keys // are returned in lower case by GetBlobProperties. HTTP header names // are case-insensitive so case munging should not matter to other // applications either. // -// See https://msdn.microsoft.com/en-us/library/azure/ee691966.aspx -func (b BlobStorageClient) SetBlobProperties(container, name string, blobHeaders BlobHeaders) error { +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Set-Blob-Properties +func (b *Blob) SetProperties(options *SetBlobPropertiesOptions) error { params := url.Values{"comp": {"properties"}} - uri := b.client.getEndpoint(blobServiceName, pathForBlob(container, name), params) - headers := b.client.getStandardHeaders() - - extraHeaders := headersFromStruct(blobHeaders) - - for k, v := range extraHeaders { - headers[k] = v + headers := b.Container.bsc.client.getStandardHeaders() + headers = mergeHeaders(headers, headersFromStruct(b.Properties)) + + if options != nil { + params = addTimeout(params, options.Timeout) + headers = mergeHeaders(headers, headersFromStruct(*options)) + } + uri := b.Container.bsc.client.getEndpoint(blobServiceName, b.buildPath(), params) + + if b.Properties.BlobType == BlobTypePage { + headers = addToHeaders(headers, "x-ms-blob-content-length", fmt.Sprintf("byte %v", b.Properties.ContentLength)) + if options != nil || options.SequenceNumberAction != nil { + headers = addToHeaders(headers, "x-ms-sequence-number-action", string(*options.SequenceNumberAction)) + if *options.SequenceNumberAction != SequenceNumberActionIncrement { + headers = addToHeaders(headers, "x-ms-blob-sequence-number", fmt.Sprintf("%v", b.Properties.SequenceNumber)) + } + } } - resp, err := b.client.exec("PUT", uri, headers, nil) + resp, err := b.Container.bsc.client.exec(http.MethodPut, uri, headers, nil, b.Container.bsc.auth) if err != nil { return err } - defer resp.body.Close() - + readAndCloseBody(resp.body) return checkRespCode(resp.statusCode, []int{http.StatusOK}) } -// SetBlobMetadata replaces the metadata for the specified blob. +// SetBlobMetadataOptions includes the options for a set blob metadata operation +type SetBlobMetadataOptions struct { + Timeout uint + LeaseID string `header:"x-ms-lease-id"` + IfModifiedSince *time.Time `header:"If-Modified-Since"` + IfUnmodifiedSince *time.Time `header:"If-Unmodified-Since"` + IfMatch string `header:"If-Match"` + IfNoneMatch string `header:"If-None-Match"` + RequestID string `header:"x-ms-client-request-id"` +} + +// SetMetadata replaces the metadata for the specified blob. // // Some keys may be converted to Camel-Case before sending. All keys // are returned in lower case by GetBlobMetadata. HTTP header names @@ -992,50 +461,71 @@ func (b BlobStorageClient) SetBlobProperties(container, name string, blobHeaders // applications either. // // See https://msdn.microsoft.com/en-us/library/azure/dd179414.aspx -func (b BlobStorageClient) SetBlobMetadata(container, name string, metadata map[string]string, extraHeaders map[string]string) error { +func (b *Blob) SetMetadata(options *SetBlobMetadataOptions) 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 := b.Container.bsc.client.getStandardHeaders() + headers = b.Container.bsc.client.addMetadataToHeaders(headers, b.Metadata) - for k, v := range extraHeaders { - headers[k] = v + if options != nil { + params = addTimeout(params, options.Timeout) + headers = mergeHeaders(headers, headersFromStruct(*options)) } + uri := b.Container.bsc.client.getEndpoint(blobServiceName, b.buildPath(), params) - resp, err := b.client.exec("PUT", uri, headers, nil) + resp, err := b.Container.bsc.client.exec(http.MethodPut, uri, headers, nil, b.Container.bsc.auth) if err != nil { return err } - defer resp.body.Close() - + readAndCloseBody(resp.body) return checkRespCode(resp.statusCode, []int{http.StatusOK}) } -// GetBlobMetadata returns all user-defined metadata for the specified blob. +// GetBlobMetadataOptions includes the options for a get blob metadata operation +type GetBlobMetadataOptions struct { + Timeout uint + Snapshot *time.Time + LeaseID string `header:"x-ms-lease-id"` + IfModifiedSince *time.Time `header:"If-Modified-Since"` + IfUnmodifiedSince *time.Time `header:"If-Unmodified-Since"` + IfMatch string `header:"If-Match"` + IfNoneMatch string `header:"If-None-Match"` + RequestID string `header:"x-ms-client-request-id"` +} + +// GetMetadata returns all user-defined metadata for the specified blob. // // All metadata keys will be returned in lower case. (HTTP header // names are case-insensitive.) // // See https://msdn.microsoft.com/en-us/library/azure/dd179414.aspx -func (b BlobStorageClient) GetBlobMetadata(container, name string) (map[string]string, error) { +func (b *Blob) GetMetadata(options *GetBlobMetadataOptions) error { params := url.Values{"comp": {"metadata"}} - uri := b.client.getEndpoint(blobServiceName, pathForBlob(container, name), params) - headers := b.client.getStandardHeaders() + headers := b.Container.bsc.client.getStandardHeaders() + + if options != nil { + params = addTimeout(params, options.Timeout) + params = addSnapshot(params, options.Snapshot) + headers = mergeHeaders(headers, headersFromStruct(*options)) + } + uri := b.Container.bsc.client.getEndpoint(blobServiceName, b.buildPath(), params) - resp, err := b.client.exec("GET", uri, headers, nil) + resp, err := b.Container.bsc.client.exec(http.MethodGet, uri, headers, nil, b.Container.bsc.auth) if err != nil { - return nil, err + return err } - defer resp.body.Close() + defer readAndCloseBody(resp.body) if err := checkRespCode(resp.statusCode, []int{http.StatusOK}); err != nil { - return nil, err + return err } + b.writeMetadata(resp.headers) + return nil +} + +func (b *Blob) writeMetadata(h http.Header) { metadata := make(map[string]string) - for k, v := range resp.headers { + for k, v := range h { // Can't trust CanonicalHeaderKey() to munge case // reliably. "_" is allowed in identifiers: // https://msdn.microsoft.com/en-us/library/azure/dd179414.aspx @@ -1044,377 +534,53 @@ func (b BlobStorageClient) GetBlobMetadata(container, name string) (map[string]s // ...but "_" is considered invalid by // CanonicalMIMEHeaderKey in // https://golang.org/src/net/textproto/reader.go?s=14615:14659#L542 - // so k can be "X-Ms-Meta-Foo" or "x-ms-meta-foo_bar". + // so k can be "X-Ms-Meta-Lol" or "x-ms-meta-lol_rofl". k = strings.ToLower(k) if len(v) == 0 || !strings.HasPrefix(k, strings.ToLower(userDefinedMetadataHeaderPrefix)) { continue } - // metadata["foo"] = content of the last X-Ms-Meta-Foo header + // metadata["lol"] = content of the last X-Ms-Meta-Lol header k = k[len(userDefinedMetadataHeaderPrefix):] metadata[k] = v[len(v)-1] } - return metadata, nil -} - -// CreateBlockBlob initializes an empty block blob with no blocks. -// -// See https://msdn.microsoft.com/en-us/library/azure/dd179451.aspx -func (b BlobStorageClient) CreateBlockBlob(container, name string) error { - return b.CreateBlockBlobFromReader(container, name, 0, nil, nil) -} - -// CreateBlockBlobFromReader initializes a block blob using data from -// reader. Size must be the number of bytes read from reader. To -// create an empty blob, use size==0 and reader==nil. -// -// The API rejects requests with size > 64 MiB (but this limit is not -// checked by the SDK). To write a larger blob, use CreateBlockBlob, -// PutBlock, and PutBlockList. -// -// See https://msdn.microsoft.com/en-us/library/azure/dd179451.aspx -func (b BlobStorageClient) CreateBlockBlobFromReader(container, name string, size uint64, blob io.Reader, 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(BlobTypeBlock) - headers["Content-Length"] = fmt.Sprintf("%d", size) - - for k, v := range extraHeaders { - headers[k] = v - } - - resp, err := b.client.exec("PUT", uri, headers, blob) - if err != nil { - return err - } - defer resp.body.Close() - return checkRespCode(resp.statusCode, []int{http.StatusCreated}) -} - -// PutBlock saves the given data chunk to the specified block blob with -// given ID. -// -// The API rejects chunks larger than 4 MiB (but this limit is not -// checked by the SDK). -// -// See https://msdn.microsoft.com/en-us/library/azure/dd135726.aspx -func (b BlobStorageClient) PutBlock(container, name, blockID string, chunk []byte) error { - return b.PutBlockWithLength(container, name, blockID, uint64(len(chunk)), bytes.NewReader(chunk), nil) -} - -// PutBlockWithLength saves the given data stream of exactly specified size to -// the block blob with given ID. It is an alternative to PutBlocks where data -// comes as stream but the length is known in advance. -// -// The API rejects requests with size > 4 MiB (but this limit is not -// checked by the SDK). -// -// See https://msdn.microsoft.com/en-us/library/azure/dd135726.aspx -func (b BlobStorageClient) PutBlockWithLength(container, name, blockID string, size uint64, blob io.Reader, extraHeaders map[string]string) error { - uri := b.client.getEndpoint(blobServiceName, pathForBlob(container, name), url.Values{"comp": {"block"}, "blockid": {blockID}}) - headers := b.client.getStandardHeaders() - headers["x-ms-blob-type"] = string(BlobTypeBlock) - headers["Content-Length"] = fmt.Sprintf("%v", size) - - for k, v := range extraHeaders { - headers[k] = v - } - - resp, err := b.client.exec("PUT", uri, headers, blob) - if err != nil { - return err - } - - defer resp.body.Close() - return checkRespCode(resp.statusCode, []int{http.StatusCreated}) -} - -// PutBlockList saves list of blocks to the specified block blob. -// -// See https://msdn.microsoft.com/en-us/library/azure/dd179467.aspx -func (b BlobStorageClient) PutBlockList(container, name string, blocks []Block) error { - blockListXML := prepareBlockListRequest(blocks) - - uri := b.client.getEndpoint(blobServiceName, pathForBlob(container, name), url.Values{"comp": {"blocklist"}}) - headers := b.client.getStandardHeaders() - headers["Content-Length"] = fmt.Sprintf("%v", len(blockListXML)) - - resp, err := b.client.exec("PUT", uri, headers, strings.NewReader(blockListXML)) - if err != nil { - return err - } - defer resp.body.Close() - return checkRespCode(resp.statusCode, []int{http.StatusCreated}) -} - -// GetBlockList retrieves list of blocks in the specified block blob. -// -// See https://msdn.microsoft.com/en-us/library/azure/dd179400.aspx -func (b BlobStorageClient) GetBlockList(container, name string, blockType BlockListType) (BlockListResponse, error) { - params := url.Values{"comp": {"blocklist"}, "blocklisttype": {string(blockType)}} - uri := b.client.getEndpoint(blobServiceName, pathForBlob(container, name), params) - headers := b.client.getStandardHeaders() - - var out BlockListResponse - resp, err := b.client.exec("GET", uri, headers, nil) - if err != nil { - return out, err - } - defer resp.body.Close() - - err = xmlUnmarshal(resp.body, &out) - return out, err -} - -// PutPageBlob initializes an empty page blob with specified name and maximum -// size in bytes (size must be aligned to a 512-byte boundary). A page blob must -// be created using this method before writing pages. -// -// See https://msdn.microsoft.com/en-us/library/azure/dd179451.aspx -func (b BlobStorageClient) PutPageBlob(container, name string, size int64, 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(BlobTypePage) - headers["x-ms-blob-content-length"] = fmt.Sprintf("%v", size) - - 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}) -} - -// PutPage writes a range of pages to a page blob or clears the given range. -// In case of 'clear' writes, given chunk is discarded. Ranges must be aligned -// 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, 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 { - contentLength = 0 - data = bytes.NewReader([]byte{}) - } else { - contentLength = int64(len(chunk)) - data = bytes.NewReader(chunk) - } - headers["Content-Length"] = fmt.Sprintf("%v", contentLength) - - resp, err := b.client.exec("PUT", uri, headers, data) - if err != nil { - return err - } - defer resp.body.Close() - - return checkRespCode(resp.statusCode, []int{http.StatusCreated}) -} - -// GetPageRanges returns the list of valid page ranges for a page blob. -// -// See https://msdn.microsoft.com/en-us/library/azure/ee691973.aspx -func (b BlobStorageClient) GetPageRanges(container, name string) (GetPageRangesResponse, error) { - path := fmt.Sprintf("%s/%s", container, name) - uri := b.client.getEndpoint(blobServiceName, path, url.Values{"comp": {"pagelist"}}) - headers := b.client.getStandardHeaders() - - var out GetPageRangesResponse - resp, err := b.client.exec("GET", uri, headers, nil) - if err != nil { - return out, err - } - defer resp.body.Close() - if err := checkRespCode(resp.statusCode, []int{http.StatusOK}); err != nil { - return out, err - } - err = xmlUnmarshal(resp.body, &out) - return out, err + b.Metadata = BlobMetadata(metadata) } -// 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}) +// DeleteBlobOptions includes the options for a delete blob operation +type DeleteBlobOptions struct { + Timeout uint + Snapshot *time.Time + LeaseID string `header:"x-ms-lease-id"` + DeleteSnapshots *bool + IfModifiedSince *time.Time `header:"If-Modified-Since"` + IfUnmodifiedSince *time.Time `header:"If-Unmodified-Since"` + IfMatch string `header:"If-Match"` + IfNoneMatch string `header:"If-None-Match"` + RequestID string `header:"x-ms-client-request-id"` } -// 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 -// this helper method works faster on smaller files. -// -// See https://msdn.microsoft.com/en-us/library/azure/dd894037.aspx -func (b BlobStorageClient) CopyBlob(container, name, sourceBlob string) error { - copyID, err := b.StartBlobCopy(container, name, sourceBlob) - if err != nil { - return err - } - - return b.WaitForBlobCopy(container, name, copyID) -} - -// StartBlobCopy starts a blob copy operation. -// sourceBlob parameter must be a canonical URL to the blob (can be -// obtained using GetBlobURL method.) -// -// See https://msdn.microsoft.com/en-us/library/azure/dd894037.aspx -func (b BlobStorageClient) StartBlobCopy(container, name, sourceBlob string) (string, error) { - uri := b.client.getEndpoint(blobServiceName, pathForBlob(container, name), url.Values{}) - - headers := b.client.getStandardHeaders() - headers["x-ms-copy-source"] = sourceBlob - - resp, err := b.client.exec("PUT", uri, headers, nil) - if err != nil { - return "", err - } - defer resp.body.Close() - - if err := checkRespCode(resp.statusCode, []int{http.StatusAccepted, http.StatusCreated}); err != nil { - return "", err - } - - copyID := resp.headers.Get("x-ms-copy-id") - if copyID == "" { - return "", errors.New("Got empty copy id header") - } - return copyID, nil -} - -// AbortBlobCopy aborts a BlobCopy which has already been triggered by the StartBlobCopy function. -// copyID is generated from StartBlobCopy function. -// currentLeaseID is required IF the destination blob has an active lease on it. -// As defined in https://msdn.microsoft.com/en-us/library/azure/jj159098.aspx -func (b BlobStorageClient) AbortBlobCopy(container, name, copyID, currentLeaseID string, timeout int) error { - params := url.Values{"comp": {"copy"}, "copyid": {copyID}} - if timeout > 0 { - params.Add("timeout", strconv.Itoa(timeout)) - } - - uri := b.client.getEndpoint(blobServiceName, pathForBlob(container, name), params) - headers := b.client.getStandardHeaders() - headers["x-ms-copy-action"] = "abort" - - if currentLeaseID != "" { - headers[leaseID] = currentLeaseID - } - - resp, err := b.client.exec("PUT", 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 -} - -// WaitForBlobCopy loops until a BlobCopy operation is completed (or fails with error) -func (b BlobStorageClient) WaitForBlobCopy(container, name, copyID string) error { - for { - props, err := b.GetBlobProperties(container, name) - if err != nil { - return err - } - - if props.CopyID != copyID { - return errBlobCopyIDMismatch - } - - switch props.CopyStatus { - case blobCopyStatusSuccess: - return nil - case blobCopyStatusPending: - continue - case blobCopyStatusAborted: - return errBlobCopyAborted - case blobCopyStatusFailed: - return fmt.Errorf("storage: blob copy failed. Id=%s Description=%s", props.CopyID, props.CopyStatusDescription) - default: - return fmt.Errorf("storage: unhandled blob copy status: '%s'", props.CopyStatus) - } - } -} - -// DeleteBlob deletes the given blob from the specified container. +// Delete 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, extraHeaders map[string]string) error { - resp, err := b.deleteBlob(container, name, extraHeaders) +// returns error. +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Delete-Blob +func (b *Blob) Delete(options *DeleteBlobOptions) error { + resp, err := b.delete(options) if err != nil { return err } - defer resp.body.Close() + readAndCloseBody(resp.body) return checkRespCode(resp.statusCode, []int{http.StatusAccepted}) } -// DeleteBlobIfExists deletes the given blob from the specified container If the +// DeleteIfExists deletes the given blob from the specified container If the // 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, extraHeaders map[string]string) (bool, error) { - resp, err := b.deleteBlob(container, name, extraHeaders) +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Delete-Blob +func (b *Blob) DeleteIfExists(options *DeleteBlobOptions) (bool, error) { + resp, err := b.delete(options) if resp != nil { - defer resp.body.Close() + defer readAndCloseBody(resp.body) if resp.statusCode == http.StatusAccepted || resp.statusCode == http.StatusNotFound { return resp.statusCode == http.StatusAccepted, nil } @@ -1422,175 +588,30 @@ func (b BlobStorageClient) DeleteBlobIfExists(container, name string, extraHeade return false, err } -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) -} - -// helper method to construct the path to a container given its name -func pathForContainer(name string) string { - return fmt.Sprintf("/%s", name) -} - -// helper method to construct the path to a blob given its container and blob -// name -func pathForBlob(container, name string) string { - return fmt.Sprintf("/%s/%s", container, name) -} - -// GetBlobSASURIWithSignedIPAndProtocol creates an URL to the specified blob which contains the Shared -// Access Signature with specified permissions and expiration time. Also includes signedIPRange and allowed procotols. -// If old API version is used but no signedIP is passed (ie empty string) then this should still work. -// We only populate the signedIP when it non-empty. -// -// See https://msdn.microsoft.com/en-us/library/azure/ee395415.aspx -func (b BlobStorageClient) GetBlobSASURIWithSignedIPAndProtocol(container, name string, expiry time.Time, permissions string, signedIPRange string, HTTPSOnly bool) (string, error) { - var ( - signedPermissions = permissions - blobURL = b.GetBlobURL(container, name) - ) - canonicalizedResource, err := b.client.buildCanonicalizedResource(blobURL) - if err != nil { - return "", err - } - - // "The canonicalizedresouce portion of the string is a canonical path to the signed resource. - // It must include the service name (blob, table, queue or file) for version 2015-02-21 or - // later, the storage account name, and the resource name, and must be URL-decoded. - // -- https://msdn.microsoft.com/en-us/library/azure/dn140255.aspx - - // We need to replace + with %2b first to avoid being treated as a space (which is correct for query strings, but not the path component). - canonicalizedResource = strings.Replace(canonicalizedResource, "+", "%2b", -1) - canonicalizedResource, err = url.QueryUnescape(canonicalizedResource) - if err != nil { - return "", err - } - - signedExpiry := expiry.UTC().Format(time.RFC3339) - signedResource := "b" - - protocols := "https,http" - if HTTPSOnly { - protocols = "https" - } - stringToSign, err := blobSASStringToSign(b.client.apiVersion, canonicalizedResource, signedExpiry, signedPermissions, signedIPRange, protocols) - if err != nil { - return "", err - } - - sig := b.client.computeHmac256(stringToSign) - sasParams := url.Values{ - "sv": {b.client.apiVersion}, - "se": {signedExpiry}, - "sr": {signedResource}, - "sp": {signedPermissions}, - "sig": {sig}, - } - - if b.client.apiVersion >= "2015-04-05" { - sasParams.Add("spr", protocols) - if signedIPRange != "" { - sasParams.Add("sip", signedIPRange) +func (b *Blob) delete(options *DeleteBlobOptions) (*storageResponse, error) { + params := url.Values{} + headers := b.Container.bsc.client.getStandardHeaders() + + if options != nil { + params = addTimeout(params, options.Timeout) + params = addSnapshot(params, options.Snapshot) + headers = mergeHeaders(headers, headersFromStruct(*options)) + if options.DeleteSnapshots != nil { + if *options.DeleteSnapshots { + headers["x-ms-delete-snapshots"] = "include" + } else { + headers["x-ms-delete-snapshots"] = "only" + } } } - - sasURL, err := url.Parse(blobURL) - if err != nil { - return "", err - } - sasURL.RawQuery = sasParams.Encode() - return sasURL.String(), nil -} - -// GetBlobSASURI creates an URL to the specified blob which contains the Shared -// Access Signature with specified permissions and expiration time. -// -// See https://msdn.microsoft.com/en-us/library/azure/ee395415.aspx -func (b BlobStorageClient) GetBlobSASURI(container, name string, expiry time.Time, permissions string) (string, error) { - url, err := b.GetBlobSASURIWithSignedIPAndProtocol(container, name, expiry, permissions, "", false) - return url, err -} - -func blobSASStringToSign(signedVersion, canonicalizedResource, signedExpiry, signedPermissions string, signedIP string, protocols string) (string, error) { - var signedStart, signedIdentifier, rscc, rscd, rsce, rscl, rsct string - - if signedVersion >= "2015-02-21" { - canonicalizedResource = "/blob" + canonicalizedResource - } - - // https://msdn.microsoft.com/en-us/library/azure/dn140255.aspx#Anchor_12 - if signedVersion >= "2015-04-05" { - return 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", signedPermissions, signedStart, signedExpiry, canonicalizedResource, signedIdentifier, signedIP, protocols, signedVersion, rscc, rscd, rsce, rscl, rsct), nil - } - - // 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 - } - - return "", errors.New("storage: not implemented SAS for versions earlier than 2013-08-15") -} - -func generatePermissions(accessPolicy AccessPolicyDetails) (permissions string) { - // generate the permissions string (rwd). - // still want the end user API to have bool flags. - permissions = "" - - if accessPolicy.CanRead { - permissions += "r" - } - - if accessPolicy.CanWrite { - permissions += "w" - } - - if accessPolicy.CanDelete { - permissions += "d" - } - - return permissions + uri := b.Container.bsc.client.getEndpoint(blobServiceName, b.buildPath(), params) + return b.Container.bsc.client.exec(http.MethodDelete, uri, headers, nil, b.Container.bsc.auth) } -// convertAccessPolicyToXMLStructs converts between AccessPolicyDetails which is a struct better for API usage to the -// AccessPolicy struct which will get converted to XML. -func convertAccessPolicyToXMLStructs(accessPolicy AccessPolicyDetails) SignedIdentifiers { - return SignedIdentifiers{ - SignedIdentifiers: []SignedIdentifier{ - { - ID: accessPolicy.ID, - AccessPolicy: AccessPolicyDetailsXML{ - StartTime: accessPolicy.StartTime.UTC().Round(time.Second), - ExpiryTime: accessPolicy.ExpiryTime.UTC().Round(time.Second), - Permission: generatePermissions(accessPolicy), - }, - }, - }, +// helper method to construct the path to either a blob or container +func pathForResource(container, name string) string { + if name != "" { + return fmt.Sprintf("/%s/%s", container, name) } -} - -// generateAccessPolicy generates the XML access policy used as the payload for SetContainerPermissions. -func generateAccessPolicy(accessPolicy AccessPolicyDetails) (accessPolicyXML string, err error) { - - if accessPolicy.ID != "" { - signedIdentifiers := convertAccessPolicyToXMLStructs(accessPolicy) - body, _, err := xmlMarshal(signedIdentifiers) - if err != nil { - return "", err - } - - xmlByteArray, err := ioutil.ReadAll(body) - if err != nil { - return "", err - } - accessPolicyXML = string(xmlByteArray) - return accessPolicyXML, nil - } - - return "", nil + return fmt.Sprintf("/%s", container) } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/blobsasuri.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/blobsasuri.go new file mode 100644 index 000000000000..43173d3a417a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/blobsasuri.go @@ -0,0 +1,106 @@ +package storage + +import ( + "errors" + "fmt" + "net/url" + "strings" + "time" +) + +// GetSASURIWithSignedIPAndProtocol creates an URL to the specified blob which contains the Shared +// Access Signature with specified permissions and expiration time. Also includes signedIPRange and allowed protocols. +// If old API version is used but no signedIP is passed (ie empty string) then this should still work. +// We only populate the signedIP when it non-empty. +// +// See https://msdn.microsoft.com/en-us/library/azure/ee395415.aspx +func (b *Blob) GetSASURIWithSignedIPAndProtocol(expiry time.Time, permissions string, signedIPRange string, HTTPSOnly bool) (string, error) { + var ( + signedPermissions = permissions + blobURL = b.GetURL() + ) + canonicalizedResource, err := b.Container.bsc.client.buildCanonicalizedResource(blobURL, b.Container.bsc.auth) + if err != nil { + return "", err + } + + // "The canonicalizedresouce portion of the string is a canonical path to the signed resource. + // It must include the service name (blob, table, queue or file) for version 2015-02-21 or + // later, the storage account name, and the resource name, and must be URL-decoded. + // -- https://msdn.microsoft.com/en-us/library/azure/dn140255.aspx + + // We need to replace + with %2b first to avoid being treated as a space (which is correct for query strings, but not the path component). + canonicalizedResource = strings.Replace(canonicalizedResource, "+", "%2b", -1) + canonicalizedResource, err = url.QueryUnescape(canonicalizedResource) + if err != nil { + return "", err + } + + signedExpiry := expiry.UTC().Format(time.RFC3339) + + //If blob name is missing, resource is a container + signedResource := "c" + if len(b.Name) > 0 { + signedResource = "b" + } + + protocols := "https,http" + if HTTPSOnly { + protocols = "https" + } + stringToSign, err := blobSASStringToSign(b.Container.bsc.client.apiVersion, canonicalizedResource, signedExpiry, signedPermissions, signedIPRange, protocols) + if err != nil { + return "", err + } + + sig := b.Container.bsc.client.computeHmac256(stringToSign) + sasParams := url.Values{ + "sv": {b.Container.bsc.client.apiVersion}, + "se": {signedExpiry}, + "sr": {signedResource}, + "sp": {signedPermissions}, + "sig": {sig}, + } + + if b.Container.bsc.client.apiVersion >= "2015-04-05" { + sasParams.Add("spr", protocols) + if signedIPRange != "" { + sasParams.Add("sip", signedIPRange) + } + } + + sasURL, err := url.Parse(blobURL) + if err != nil { + return "", err + } + sasURL.RawQuery = sasParams.Encode() + return sasURL.String(), nil +} + +// GetSASURI creates an URL to the specified blob which contains the Shared +// Access Signature with specified permissions and expiration time. +// +// See https://msdn.microsoft.com/en-us/library/azure/ee395415.aspx +func (b *Blob) GetSASURI(expiry time.Time, permissions string) (string, error) { + return b.GetSASURIWithSignedIPAndProtocol(expiry, permissions, "", false) +} + +func blobSASStringToSign(signedVersion, canonicalizedResource, signedExpiry, signedPermissions string, signedIP string, protocols string) (string, error) { + var signedStart, signedIdentifier, rscc, rscd, rsce, rscl, rsct string + + if signedVersion >= "2015-02-21" { + canonicalizedResource = "/blob" + canonicalizedResource + } + + // https://msdn.microsoft.com/en-us/library/azure/dn140255.aspx#Anchor_12 + if signedVersion >= "2015-04-05" { + return 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", signedPermissions, signedStart, signedExpiry, canonicalizedResource, signedIdentifier, signedIP, protocols, signedVersion, rscc, rscd, rsce, rscl, rsct), nil + } + + // 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 + } + + return "", errors.New("storage: not implemented SAS for versions earlier than 2013-08-15") +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/blobserviceclient.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/blobserviceclient.go new file mode 100644 index 000000000000..450b20f96724 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/blobserviceclient.go @@ -0,0 +1,95 @@ +package storage + +import ( + "net/http" + "net/url" + "strconv" +) + +// BlobStorageClient contains operations for Microsoft Azure Blob Storage +// Service. +type BlobStorageClient struct { + client Client + auth authentication +} + +// GetServiceProperties gets the properties of your storage account's blob service. +// See: https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/get-blob-service-properties +func (b *BlobStorageClient) GetServiceProperties() (*ServiceProperties, error) { + return b.client.getServiceProperties(blobServiceName, b.auth) +} + +// SetServiceProperties sets the properties of your storage account's blob service. +// See: https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/set-blob-service-properties +func (b *BlobStorageClient) SetServiceProperties(props ServiceProperties) error { + return b.client.setServiceProperties(props, blobServiceName, b.auth) +} + +// ListContainersParameters defines the set of customizable parameters to make a +// List Containers call. +// +// See https://msdn.microsoft.com/en-us/library/azure/dd179352.aspx +type ListContainersParameters struct { + Prefix string + Marker string + Include string + MaxResults uint + Timeout uint +} + +// GetContainerReference returns a Container object for the specified container name. +func (b *BlobStorageClient) GetContainerReference(name string) *Container { + return &Container{ + bsc: b, + Name: name, + } +} + +// ListContainers returns the list of containers in a storage account along with +// pagination token and other response details. +// +// See https://msdn.microsoft.com/en-us/library/azure/dd179352.aspx +func (b BlobStorageClient) ListContainers(params ListContainersParameters) (*ContainerListResponse, error) { + q := mergeParams(params.getParameters(), url.Values{"comp": {"list"}}) + uri := b.client.getEndpoint(blobServiceName, "", q) + headers := b.client.getStandardHeaders() + + var out ContainerListResponse + resp, err := b.client.exec(http.MethodGet, uri, headers, nil, b.auth) + if err != nil { + return nil, err + } + defer resp.body.Close() + err = xmlUnmarshal(resp.body, &out) + if err != nil { + return nil, err + } + + // assign our client to the newly created Container objects + for i := range out.Containers { + out.Containers[i].bsc = &b + } + return &out, err +} + +func (p ListContainersParameters) getParameters() url.Values { + out := url.Values{} + + if p.Prefix != "" { + out.Set("prefix", p.Prefix) + } + if p.Marker != "" { + out.Set("marker", p.Marker) + } + if p.Include != "" { + out.Set("include", p.Include) + } + if p.MaxResults != 0 { + out.Set("maxresults", strconv.FormatUint(uint64(p.MaxResults), 10)) + } + if p.Timeout != 0 { + out.Set("timeout", strconv.FormatUint(uint64(p.Timeout), 10)) + } + + return out +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/blockblob.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/blockblob.go new file mode 100644 index 000000000000..6a180d48d7cb --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/blockblob.go @@ -0,0 +1,240 @@ +package storage + +import ( + "bytes" + "encoding/xml" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "strings" + "time" +) + +// BlockListType is used to filter out types of blocks in a Get Blocks List call +// for a block blob. +// +// See https://msdn.microsoft.com/en-us/library/azure/dd179400.aspx for all +// block types. +type BlockListType string + +// Filters for listing blocks in block blobs +const ( + BlockListTypeAll BlockListType = "all" + BlockListTypeCommitted BlockListType = "committed" + BlockListTypeUncommitted BlockListType = "uncommitted" +) + +// Maximum sizes (per REST API) for various concepts +const ( + MaxBlobBlockSize = 100 * 1024 * 1024 + MaxBlobPageSize = 4 * 1024 * 1024 +) + +// BlockStatus defines states a block for a block blob can +// be in. +type BlockStatus string + +// List of statuses that can be used to refer to a block in a block list +const ( + BlockStatusUncommitted BlockStatus = "Uncommitted" + BlockStatusCommitted BlockStatus = "Committed" + BlockStatusLatest BlockStatus = "Latest" +) + +// Block is used to create Block entities for Put Block List +// call. +type Block struct { + ID string + Status BlockStatus +} + +// BlockListResponse contains the response fields from Get Block List call. +// +// See https://msdn.microsoft.com/en-us/library/azure/dd179400.aspx +type BlockListResponse struct { + XMLName xml.Name `xml:"BlockList"` + CommittedBlocks []BlockResponse `xml:"CommittedBlocks>Block"` + UncommittedBlocks []BlockResponse `xml:"UncommittedBlocks>Block"` +} + +// BlockResponse contains the block information returned +// in the GetBlockListCall. +type BlockResponse struct { + Name string `xml:"Name"` + Size int64 `xml:"Size"` +} + +// CreateBlockBlob initializes an empty block blob with no blocks. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Put-Blob +func (b *Blob) CreateBlockBlob(options *PutBlobOptions) error { + return b.CreateBlockBlobFromReader(nil, options) +} + +// CreateBlockBlobFromReader initializes a block blob using data from +// reader. Size must be the number of bytes read from reader. To +// create an empty blob, use size==0 and reader==nil. +// +// The API rejects requests with size > 256 MiB (but this limit is not +// checked by the SDK). To write a larger blob, use CreateBlockBlob, +// PutBlock, and PutBlockList. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Put-Blob +func (b *Blob) CreateBlockBlobFromReader(blob io.Reader, options *PutBlobOptions) error { + params := url.Values{} + headers := b.Container.bsc.client.getStandardHeaders() + headers["x-ms-blob-type"] = string(BlobTypeBlock) + + headers["Content-Length"] = "0" + var n int64 + var err error + if blob != nil { + buf := &bytes.Buffer{} + n, err = io.Copy(buf, blob) + if err != nil { + return err + } + blob = buf + headers["Content-Length"] = strconv.FormatInt(n, 10) + } + b.Properties.ContentLength = n + + headers = mergeHeaders(headers, headersFromStruct(b.Properties)) + headers = b.Container.bsc.client.addMetadataToHeaders(headers, b.Metadata) + + if options != nil { + params = addTimeout(params, options.Timeout) + headers = mergeHeaders(headers, headersFromStruct(*options)) + } + uri := b.Container.bsc.client.getEndpoint(blobServiceName, b.buildPath(), params) + + resp, err := b.Container.bsc.client.exec(http.MethodPut, uri, headers, blob, b.Container.bsc.auth) + if err != nil { + return err + } + readAndCloseBody(resp.body) + return checkRespCode(resp.statusCode, []int{http.StatusCreated}) +} + +// PutBlockOptions includes the options for a put block operation +type PutBlockOptions struct { + Timeout uint + LeaseID string `header:"x-ms-lease-id"` + ContentMD5 string `header:"Content-MD5"` + RequestID string `header:"x-ms-client-request-id"` +} + +// PutBlock saves the given data chunk to the specified block blob with +// given ID. +// +// The API rejects chunks larger than 100 MiB (but this limit is not +// checked by the SDK). +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Put-Block +func (b *Blob) PutBlock(blockID string, chunk []byte, options *PutBlockOptions) error { + return b.PutBlockWithLength(blockID, uint64(len(chunk)), bytes.NewReader(chunk), options) +} + +// PutBlockWithLength saves the given data stream of exactly specified size to +// the block blob with given ID. It is an alternative to PutBlocks where data +// comes as stream but the length is known in advance. +// +// The API rejects requests with size > 100 MiB (but this limit is not +// checked by the SDK). +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Put-Block +func (b *Blob) PutBlockWithLength(blockID string, size uint64, blob io.Reader, options *PutBlockOptions) error { + query := url.Values{ + "comp": {"block"}, + "blockid": {blockID}, + } + headers := b.Container.bsc.client.getStandardHeaders() + headers["Content-Length"] = fmt.Sprintf("%v", size) + + if options != nil { + query = addTimeout(query, options.Timeout) + headers = mergeHeaders(headers, headersFromStruct(*options)) + } + uri := b.Container.bsc.client.getEndpoint(blobServiceName, b.buildPath(), query) + + resp, err := b.Container.bsc.client.exec(http.MethodPut, uri, headers, blob, b.Container.bsc.auth) + if err != nil { + return err + } + readAndCloseBody(resp.body) + return checkRespCode(resp.statusCode, []int{http.StatusCreated}) +} + +// PutBlockListOptions includes the options for a put block list operation +type PutBlockListOptions struct { + Timeout uint + LeaseID string `header:"x-ms-lease-id"` + IfModifiedSince *time.Time `header:"If-Modified-Since"` + IfUnmodifiedSince *time.Time `header:"If-Unmodified-Since"` + IfMatch string `header:"If-Match"` + IfNoneMatch string `header:"If-None-Match"` + RequestID string `header:"x-ms-client-request-id"` +} + +// PutBlockList saves list of blocks to the specified block blob. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Put-Block-List +func (b *Blob) PutBlockList(blocks []Block, options *PutBlockListOptions) error { + params := url.Values{"comp": {"blocklist"}} + blockListXML := prepareBlockListRequest(blocks) + headers := b.Container.bsc.client.getStandardHeaders() + headers["Content-Length"] = fmt.Sprintf("%v", len(blockListXML)) + headers = mergeHeaders(headers, headersFromStruct(b.Properties)) + headers = b.Container.bsc.client.addMetadataToHeaders(headers, b.Metadata) + + if options != nil { + params = addTimeout(params, options.Timeout) + headers = mergeHeaders(headers, headersFromStruct(*options)) + } + uri := b.Container.bsc.client.getEndpoint(blobServiceName, b.buildPath(), params) + + resp, err := b.Container.bsc.client.exec(http.MethodPut, uri, headers, strings.NewReader(blockListXML), b.Container.bsc.auth) + if err != nil { + return err + } + readAndCloseBody(resp.body) + return checkRespCode(resp.statusCode, []int{http.StatusCreated}) +} + +// GetBlockListOptions includes the options for a get block list operation +type GetBlockListOptions struct { + Timeout uint + Snapshot *time.Time + LeaseID string `header:"x-ms-lease-id"` + RequestID string `header:"x-ms-client-request-id"` +} + +// GetBlockList retrieves list of blocks in the specified block blob. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Get-Block-List +func (b *Blob) GetBlockList(blockType BlockListType, options *GetBlockListOptions) (BlockListResponse, error) { + params := url.Values{ + "comp": {"blocklist"}, + "blocklisttype": {string(blockType)}, + } + headers := b.Container.bsc.client.getStandardHeaders() + + if options != nil { + params = addTimeout(params, options.Timeout) + params = addSnapshot(params, options.Snapshot) + headers = mergeHeaders(headers, headersFromStruct(*options)) + } + uri := b.Container.bsc.client.getEndpoint(blobServiceName, b.buildPath(), params) + + var out BlockListResponse + resp, err := b.Container.bsc.client.exec(http.MethodGet, uri, headers, nil, b.Container.bsc.auth) + if err != nil { + return out, err + } + defer resp.body.Close() + + err = xmlUnmarshal(resp.body, &out) + return out, err +} 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 77528511a47a..8671e52eb71f 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 @@ -2,6 +2,7 @@ package storage import ( + "bufio" "bytes" "encoding/base64" "encoding/json" @@ -10,22 +11,27 @@ import ( "fmt" "io" "io/ioutil" + "mime" + "mime/multipart" "net/http" "net/url" "regexp" - "sort" - "strconv" + "runtime" "strings" + "time" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" ) const ( - // DefaultBaseURL is the domain name used for storage requests when a - // default client is created. + // DefaultBaseURL is the domain name used for storage requests in the + // public cloud when a default client is created. DefaultBaseURL = "core.windows.net" - // DefaultAPIVersion is the Azure Storage API version string used when a + // DefaultAPIVersion is the Azure Storage API version string used when a // basic client is created. - DefaultAPIVersion = "2015-02-21" + DefaultAPIVersion = "2016-05-31" defaultUseHTTPS = true @@ -43,20 +49,75 @@ const ( storageEmulatorBlob = "127.0.0.1:10000" storageEmulatorTable = "127.0.0.1:10002" storageEmulatorQueue = "127.0.0.1:10001" + + userAgentHeader = "User-Agent" + + userDefinedMetadataHeaderPrefix = "x-ms-meta-" ) +var ( + validStorageAccount = regexp.MustCompile("^[0-9a-z]{3,24}$") +) + +// Sender sends a request +type Sender interface { + Send(*Client, *http.Request) (*http.Response, error) +} + +// DefaultSender is the default sender for the client. It implements +// an automatic retry strategy. +type DefaultSender struct { + RetryAttempts int + RetryDuration time.Duration + ValidStatusCodes []int + attempts int // used for testing +} + +// Send is the default retry strategy in the client +func (ds *DefaultSender) Send(c *Client, req *http.Request) (resp *http.Response, err error) { + b := []byte{} + if req.Body != nil { + b, err = ioutil.ReadAll(req.Body) + if err != nil { + return resp, err + } + } + + for attempts := 0; attempts < ds.RetryAttempts; attempts++ { + if len(b) > 0 { + req.Body = ioutil.NopCloser(bytes.NewBuffer(b)) + } + resp, err = c.HTTPClient.Do(req) + if err != nil || !autorest.ResponseHasStatusCode(resp, ds.ValidStatusCodes...) { + return resp, err + } + autorest.DelayForBackoff(ds.RetryDuration, attempts, req.Cancel) + ds.attempts = attempts + } + ds.attempts++ + return resp, err +} + // 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. + // requests. http.DefaultClient is used when creating a + // client. HTTPClient *http.Client - accountName string - accountKey []byte - useHTTPS bool - baseURL string - apiVersion string + // Sender is an interface that sends the request. Clients are + // created with a DefaultSender. The DefaultSender has an + // automatic retry strategy built in. The Sender can be customized. + Sender Sender + + accountName string + accountKey []byte + useHTTPS bool + UseSharedKeyLite bool + baseURL string + apiVersion string + userAgent string } type storageResponse struct { @@ -67,7 +128,7 @@ type storageResponse struct { type odataResponse struct { storageResponse - odata odataErrorMessage + odata odataErrorWrapper } // AzureStorageServiceError contains fields of the error response from @@ -80,22 +141,25 @@ type AzureStorageServiceError struct { QueryParameterName string `xml:"QueryParameterName"` QueryParameterValue string `xml:"QueryParameterValue"` Reason string `xml:"Reason"` + Lang string StatusCode int RequestID string + Date string + APIVersion string } -type odataErrorMessageMessage struct { +type odataErrorMessage struct { Lang string `json:"lang"` Value string `json:"value"` } -type odataErrorMessageInternal struct { - Code string `json:"code"` - Message odataErrorMessageMessage `json:"message"` +type odataError struct { + Code string `json:"code"` + Message odataErrorMessage `json:"message"` } -type odataErrorMessage struct { - Err odataErrorMessageInternal `json:"odata.error"` +type odataErrorWrapper struct { + Err odataError `json:"odata.error"` } // UnexpectedStatusCodeError is returned when a storage service responds with neither an error @@ -128,7 +192,15 @@ func NewBasicClient(accountName, accountKey string) (Client, error) { return NewEmulatorClient() } return NewClient(accountName, accountKey, DefaultBaseURL, DefaultAPIVersion, defaultUseHTTPS) +} +// NewBasicClientOnSovereignCloud constructs a Client with given storage service name and +// key in the referenced cloud. +func NewBasicClientOnSovereignCloud(accountName, accountKey string, env azure.Environment) (Client, error) { + if accountName == StorageEmulatorAccountName { + return NewEmulatorClient() + } + return NewClient(accountName, accountKey, env.StorageEndpointSuffix, DefaultAPIVersion, defaultUseHTTPS) } //NewEmulatorClient contructs a Client intended to only work with Azure @@ -142,8 +214,8 @@ func NewEmulatorClient() (Client, error) { // storage endpoint than Azure Public Cloud. func NewClient(accountName, accountKey, blobServiceBaseURL, apiVersion string, useHTTPS bool) (Client, error) { var c Client - if accountName == "" { - return c, fmt.Errorf("azure: account name required") + if !IsValidStorageAccount(accountName) { + return c, fmt.Errorf("azure: account name is not valid: it must be between 3 and 24 characters, and only may contain numbers and lowercase letters: %v", accountName) } else if accountKey == "" { return c, fmt.Errorf("azure: account key required") } else if blobServiceBaseURL == "" { @@ -155,16 +227,67 @@ func NewClient(accountName, accountKey, blobServiceBaseURL, apiVersion string, u return c, fmt.Errorf("azure: malformed storage account key: %v", err) } - return Client{ - accountName: accountName, - accountKey: key, - useHTTPS: useHTTPS, - baseURL: blobServiceBaseURL, - apiVersion: apiVersion, - }, nil + c = Client{ + HTTPClient: http.DefaultClient, + accountName: accountName, + accountKey: key, + useHTTPS: useHTTPS, + baseURL: blobServiceBaseURL, + apiVersion: apiVersion, + UseSharedKeyLite: false, + Sender: &DefaultSender{ + RetryAttempts: 5, + ValidStatusCodes: []int{ + http.StatusRequestTimeout, // 408 + http.StatusInternalServerError, // 500 + http.StatusBadGateway, // 502 + http.StatusServiceUnavailable, // 503 + http.StatusGatewayTimeout, // 504 + }, + RetryDuration: time.Second * 5, + }, + } + c.userAgent = c.getDefaultUserAgent() + return c, nil } -func (c Client) getBaseURL(service string) string { +// IsValidStorageAccount checks if the storage account name is valid. +// See https://docs.microsoft.com/en-us/azure/storage/storage-create-storage-account +func IsValidStorageAccount(account string) bool { + return validStorageAccount.MatchString(account) +} + +func (c Client) getDefaultUserAgent() string { + return fmt.Sprintf("Go/%s (%s-%s) azure-storage-go/%s api-version/%s", + runtime.Version(), + runtime.GOARCH, + runtime.GOOS, + sdkVersion, + c.apiVersion, + ) +} + +// AddToUserAgent adds an extension to the current user agent +func (c *Client) AddToUserAgent(extension string) error { + if extension != "" { + c.userAgent = fmt.Sprintf("%s %s", c.userAgent, extension) + return nil + } + return fmt.Errorf("Extension was empty, User Agent stayed as %s", c.userAgent) +} + +// protectUserAgent is used in funcs that include extraheaders as a parameter. +// It prevents the User-Agent header to be overwritten, instead if it happens to +// be present, it gets added to the current User-Agent. Use it before getStandardHeaders +func (c *Client) protectUserAgent(extraheaders map[string]string) map[string]string { + if v, ok := extraheaders[userAgentHeader]; ok { + c.AddToUserAgent(v) + delete(extraheaders, userAgentHeader) + } + return extraheaders +} + +func (c Client) getBaseURL(service string) *url.URL { scheme := "http" if c.useHTTPS { scheme = "https" @@ -183,18 +306,14 @@ func (c Client) getBaseURL(service string) string { host = fmt.Sprintf("%s.%s.%s", c.accountName, service, c.baseURL) } - u := &url.URL{ + return &url.URL{ Scheme: scheme, - Host: host} - return u.String() + Host: host, + } } func (c Client) getEndpoint(service, path string, params url.Values) string { - u, err := url.Parse(c.getBaseURL(service)) - if err != nil { - // really should not be happening - panic(err) - } + u := c.getBaseURL(service) // API doesn't accept path segments not starting with '/' if !strings.HasPrefix(path, "/") { @@ -213,181 +332,69 @@ func (c Client) getEndpoint(service, path string, params url.Values) string { // GetBlobService returns a BlobStorageClient which can operate on the blob // service of the storage account. func (c Client) GetBlobService() BlobStorageClient { - return BlobStorageClient{c} + b := BlobStorageClient{ + client: c, + } + b.client.AddToUserAgent(blobServiceName) + b.auth = sharedKey + if c.UseSharedKeyLite { + b.auth = sharedKeyLite + } + return b } // GetQueueService returns a QueueServiceClient which can operate on the queue // service of the storage account. func (c Client) GetQueueService() QueueServiceClient { - return QueueServiceClient{c} + q := QueueServiceClient{ + client: c, + } + q.client.AddToUserAgent(queueServiceName) + q.auth = sharedKey + if c.UseSharedKeyLite { + q.auth = sharedKeyLite + } + return q } // GetTableService returns a TableServiceClient which can operate on the table // service of the storage account. func (c Client) GetTableService() TableServiceClient { - return TableServiceClient{c} + t := TableServiceClient{ + client: c, + } + t.client.AddToUserAgent(tableServiceName) + t.auth = sharedKeyForTable + if c.UseSharedKeyLite { + t.auth = sharedKeyLiteForTable + } + return t } // GetFileService returns a FileServiceClient which can operate on the file // service of the storage account. func (c Client) GetFileService() FileServiceClient { - return FileServiceClient{c} -} - -func (c Client) createAuthorizationHeader(canonicalizedString string) string { - signature := c.computeHmac256(canonicalizedString) - return fmt.Sprintf("%s %s:%s", "SharedKey", c.getCanonicalizedAccountName(), signature) -} - -func (c Client) getAuthorizationHeader(verb, url string, headers map[string]string) (string, error) { - canonicalizedResource, err := c.buildCanonicalizedResource(url) - if err != nil { - return "", err + f := FileServiceClient{ + client: c, } - - canonicalizedString := c.buildCanonicalizedString(verb, headers, canonicalizedResource) - return c.createAuthorizationHeader(canonicalizedString), nil + f.client.AddToUserAgent(fileServiceName) + f.auth = sharedKey + if c.UseSharedKeyLite { + f.auth = sharedKeyLite + } + return f } func (c Client) getStandardHeaders() map[string]string { return map[string]string{ - "x-ms-version": c.apiVersion, - "x-ms-date": currentTimeRfc1123Formatted(), - } -} - -func (c Client) getCanonicalizedAccountName() string { - // since we may be trying to access a secondary storage account, we need to - // remove the -secondary part of the storage name - return strings.TrimSuffix(c.accountName, "-secondary") -} - -func (c Client) buildCanonicalizedHeader(headers map[string]string) string { - cm := make(map[string]string) - - for k, v := range headers { - headerName := strings.TrimSpace(strings.ToLower(k)) - match, _ := regexp.MatchString("x-ms-", headerName) - if match { - cm[headerName] = v - } - } - - if len(cm) == 0 { - return "" - } - - keys := make([]string, 0, len(cm)) - for key := range cm { - keys = append(keys, key) - } - - sort.Strings(keys) - - ch := "" - - for i, key := range keys { - if i == len(keys)-1 { - ch += fmt.Sprintf("%s:%s", key, cm[key]) - } else { - ch += fmt.Sprintf("%s:%s\n", key, cm[key]) - } - } - 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.getCanonicalizedAccountName() - - if len(u.Path) > 0 { - cr += u.EscapedPath() - } - - return cr, nil -} - -func (c Client) buildCanonicalizedResource(uri string) (string, error) { - errMsg := "buildCanonicalizedResource error: %s" - u, err := url.Parse(uri) - if err != nil { - return "", fmt.Errorf(errMsg, err.Error()) - } - - cr := "/" + c.getCanonicalizedAccountName() - - if len(u.Path) > 0 { - // Any portion of the CanonicalizedResource string that is derived from - // the resource's URI should be encoded exactly as it is in the URI. - // -- https://msdn.microsoft.com/en-gb/library/azure/dd179428.aspx - cr += u.EscapedPath() - } - - params, err := url.ParseQuery(u.RawQuery) - if err != nil { - return "", fmt.Errorf(errMsg, err.Error()) + userAgentHeader: c.userAgent, + "x-ms-version": c.apiVersion, + "x-ms-date": currentTimeRfc1123Formatted(), } - - if len(params) > 0 { - cr += "\n" - keys := make([]string, 0, len(params)) - for key := range params { - keys = append(keys, key) - } - - sort.Strings(keys) - - for i, key := range keys { - if len(params[key]) > 1 { - sort.Strings(params[key]) - } - - if i == len(keys)-1 { - cr += fmt.Sprintf("%s:%s", key, strings.Join(params[key], ",")) - } else { - cr += fmt.Sprintf("%s:%s\n", key, strings.Join(params[key], ",")) - } - } - } - - 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"], - contentLength, - headers["Content-MD5"], - headers["Content-Type"], - headers["Date"], - headers["If-Modified-Since"], - headers["If-Match"], - headers["If-None-Match"], - headers["If-Unmodified-Since"], - headers["Range"], - c.buildCanonicalizedHeader(headers), - canonicalizedResource) - - return canonicalizedString -} - -func (c Client) exec(verb, url string, headers map[string]string, body io.Reader) (*storageResponse, error) { - authHeader, err := c.getAuthorizationHeader(verb, url, headers) - if err != nil { - return nil, err - } - headers["Authorization"] = authHeader +func (c Client) exec(verb, url string, headers map[string]string, body io.Reader, auth authentication) (*storageResponse, error) { + headers, err := c.addAuthorizationHeader(verb, url, headers, auth) if err != nil { return nil, err } @@ -397,45 +404,44 @@ func (c Client) exec(verb, url string, headers map[string]string, body io.Reader return nil, errors.New("azure/storage: error creating request: " + err.Error()) } - if clstr, ok := headers["Content-Length"]; ok { - // content length header is being signed, but completely ignored by golang. - // instead we have to use the ContentLength property on the request struct - // (see https://golang.org/src/net/http/request.go?s=18140:18370#L536 and - // https://golang.org/src/net/http/transfer.go?s=1739:2467#L49) - req.ContentLength, err = strconv.ParseInt(clstr, 10, 64) - if err != nil { - return nil, err - } - } for k, v := range headers { req.Header.Add(k, v) } - httpClient := c.HTTPClient - if httpClient == nil { - httpClient = http.DefaultClient - } - resp, err := httpClient.Do(req) + resp, err := c.Sender.Send(&c, req) if err != nil { return nil, err } - statusCode := resp.StatusCode - if statusCode >= 400 && statusCode <= 505 { + if resp.StatusCode >= 400 && resp.StatusCode <= 505 { var respBody []byte - respBody, err = readResponseBody(resp) + respBody, err = readAndCloseBody(resp.Body) if err != nil { return nil, err } + requestID, date, version := getDebugHeaders(resp.Header) if len(respBody) == 0 { - // no error in response body - err = fmt.Errorf("storage: service returned without a response body (%s)", resp.Status) + // no error in response body, might happen in HEAD requests + err = serviceErrFromStatusCode(resp.StatusCode, resp.Status, requestID, date, version) } else { + storageErr := AzureStorageServiceError{ + StatusCode: resp.StatusCode, + RequestID: requestID, + Date: date, + APIVersion: version, + } // response contains storage service error object, unmarshal - storageErr, errIn := serviceErrFromXML(respBody, resp.StatusCode, resp.Header.Get("x-ms-request-id")) - if err != nil { // error unmarshaling the error response - err = errIn + if resp.Header.Get("Content-Type") == "application/xml" { + errIn := serviceErrFromXML(respBody, &storageErr) + if err != nil { // error unmarshaling the error response + err = errIn + } + } else { + errIn := serviceErrFromJSON(respBody, &storageErr) + if err != nil { // error unmarshaling the error response + err = errIn + } } err = storageErr } @@ -452,20 +458,20 @@ 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) { +func (c Client) execInternalJSONCommon(verb, url string, headers map[string]string, body io.Reader, auth authentication) (*odataResponse, *http.Request, *http.Response, error) { + headers, err := c.addAuthorizationHeader(verb, url, headers, auth) + if err != nil { + return nil, nil, nil, err + } + 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) + resp, err := c.Sender.Send(&c, req) if err != nil { - return nil, err + return nil, nil, nil, err } respToRet := &odataResponse{} @@ -476,68 +482,155 @@ func (c Client) execInternalJSON(verb, url string, headers map[string]string, bo statusCode := resp.StatusCode if statusCode >= 400 && statusCode <= 505 { var respBody []byte - respBody, err = readResponseBody(resp) + respBody, err = readAndCloseBody(resp.Body) if err != nil { - return nil, err + return nil, nil, nil, err } + requestID, date, version := getDebugHeaders(resp.Header) 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 + // no error in response body, might happen in HEAD requests + err = serviceErrFromStatusCode(resp.StatusCode, resp.Status, requestID, date, version) + return respToRet, req, resp, err } // try unmarshal as odata.error json err = json.Unmarshal(respBody, &respToRet.odata) - return respToRet, err + } + + return respToRet, req, resp, err +} + +func (c Client) execInternalJSON(verb, url string, headers map[string]string, body io.Reader, auth authentication) (*odataResponse, error) { + respToRet, _, _, err := c.execInternalJSONCommon(verb, url, headers, body, auth) + return respToRet, err +} + +func (c Client) execBatchOperationJSON(verb, url string, headers map[string]string, body io.Reader, auth authentication) (*odataResponse, error) { + // execute common query, get back generated request, response etc... for more processing. + respToRet, req, resp, err := c.execInternalJSONCommon(verb, url, headers, body, auth) + if err != nil { + return nil, err + } + + // return the OData in the case of executing batch commands. + // In this case we need to read the outer batch boundary and contents. + // Then we read the changeset information within the batch + var respBody []byte + respBody, err = readAndCloseBody(resp.Body) + if err != nil { + return nil, err + } + + // outer multipart body + _, batchHeader, err := mime.ParseMediaType(resp.Header["Content-Type"][0]) + if err != nil { + return nil, err + } + + // batch details. + batchBoundary := batchHeader["boundary"] + batchPartBuf, changesetBoundary, err := genBatchReader(batchBoundary, respBody) + if err != nil { + return nil, err + } + + // changeset details. + err = genChangesetReader(req, respToRet, batchPartBuf, changesetBoundary) + if err != nil { + return nil, err } return respToRet, nil } -func (c Client) createSharedKeyLite(url string, headers map[string]string) (string, error) { - can, err := c.buildCanonicalizedResourceTable(url) +func genChangesetReader(req *http.Request, respToRet *odataResponse, batchPartBuf io.Reader, changesetBoundary string) error { + changesetMultiReader := multipart.NewReader(batchPartBuf, changesetBoundary) + changesetPart, err := changesetMultiReader.NextPart() + if err != nil { + return err + } + changesetPartBufioReader := bufio.NewReader(changesetPart) + changesetResp, err := http.ReadResponse(changesetPartBufioReader, req) if err != nil { - return "", err + return err + } + + if changesetResp.StatusCode != http.StatusNoContent { + changesetBody, err := readAndCloseBody(changesetResp.Body) + err = json.Unmarshal(changesetBody, &respToRet.odata) + if err != nil { + return err + } + respToRet.statusCode = changesetResp.StatusCode } - strToSign := headers["x-ms-date"] + "\n" + can - hmac := c.computeHmac256(strToSign) - return fmt.Sprintf("SharedKeyLite %s:%s", c.accountName, hmac), nil + return 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) +func genBatchReader(batchBoundary string, respBody []byte) (io.Reader, string, error) { + respBodyString := string(respBody) + respBodyReader := strings.NewReader(respBodyString) + + // reading batchresponse + batchMultiReader := multipart.NewReader(respBodyReader, batchBoundary) + batchPart, err := batchMultiReader.NextPart() if err != nil { - return nil, err + return nil, "", err } + batchPartBufioReader := bufio.NewReader(batchPart) - return c.execInternalJSON(verb, url, headers, body) + _, changesetHeader, err := mime.ParseMediaType(batchPart.Header.Get("Content-Type")) + if err != nil { + return nil, "", err + } + changesetBoundary := changesetHeader["boundary"] + return batchPartBufioReader, changesetBoundary, nil } -func readResponseBody(resp *http.Response) ([]byte, error) { - defer resp.Body.Close() - out, err := ioutil.ReadAll(resp.Body) +func readAndCloseBody(body io.ReadCloser) ([]byte, error) { + defer body.Close() + out, err := ioutil.ReadAll(body) if err == io.EOF { err = nil } return out, err } -func serviceErrFromXML(body []byte, statusCode int, requestID string) (AzureStorageServiceError, error) { - var storageErr AzureStorageServiceError - if err := xml.Unmarshal(body, &storageErr); err != nil { - return storageErr, err +func serviceErrFromXML(body []byte, storageErr *AzureStorageServiceError) error { + if err := xml.Unmarshal(body, storageErr); err != nil { + storageErr.Message = fmt.Sprintf("Response body could no be unmarshaled: %v. Body: %v.", err, string(body)) + return err + } + return nil +} + +func serviceErrFromJSON(body []byte, storageErr *AzureStorageServiceError) error { + odataError := odataErrorWrapper{} + if err := json.Unmarshal(body, &odataError); err != nil { + storageErr.Message = fmt.Sprintf("Response body could no be unmarshaled: %v. Body: %v.", err, string(body)) + return err + } + storageErr.Code = odataError.Err.Code + storageErr.Message = odataError.Err.Message.Value + storageErr.Lang = odataError.Err.Message.Lang + return nil +} + +func serviceErrFromStatusCode(code int, status string, requestID, date, version string) AzureStorageServiceError { + return AzureStorageServiceError{ + StatusCode: code, + Code: status, + RequestID: requestID, + Date: date, + APIVersion: version, + Message: "no response body was available for error status code", } - storageErr.StatusCode = statusCode - storageErr.RequestID = requestID - return storageErr, nil } func (e AzureStorageServiceError) Error() string { - return fmt.Sprintf("storage: service returned error: StatusCode=%d, ErrorCode=%s, ErrorMessage=%s, RequestId=%s, QueryParameterName=%s, QueryParameterValue=%s", - e.StatusCode, e.Code, e.Message, e.RequestID, e.QueryParameterName, e.QueryParameterValue) + return fmt.Sprintf("storage: service returned error: StatusCode=%d, ErrorCode=%s, ErrorMessage=%s, RequestInitiated=%s, RequestId=%s, API Version=%s, QueryParameterName=%s, QueryParameterValue=%s", + e.StatusCode, e.Code, e.Message, e.Date, e.RequestID, e.APIVersion, e.QueryParameterName, e.QueryParameterValue) } // checkRespCode returns UnexpectedStatusError if the given response code is not @@ -550,3 +643,18 @@ func checkRespCode(respCode int, allowed []int) error { } return UnexpectedStatusCodeError{allowed, respCode} } + +func (c Client) addMetadataToHeaders(h map[string]string, metadata map[string]string) map[string]string { + metadata = c.protectUserAgent(metadata) + for k, v := range metadata { + h[userDefinedMetadataHeaderPrefix+k] = v + } + return h +} + +func getDebugHeaders(h http.Header) (requestID, date, version string) { + requestID = h.Get("x-ms-request-id") + version = h.Get("x-ms-version") + date = h.Get("Date") + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/container.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/container.go new file mode 100644 index 000000000000..c2c9c055b562 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/container.go @@ -0,0 +1,453 @@ +package storage + +import ( + "encoding/xml" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "strings" + "time" +) + +// Container represents an Azure container. +type Container struct { + bsc *BlobStorageClient + Name string `xml:"Name"` + Properties ContainerProperties `xml:"Properties"` + Metadata map[string]string +} + +func (c *Container) buildPath() string { + return fmt.Sprintf("/%s", c.Name) +} + +// ContainerProperties contains various properties of a container returned from +// various endpoints like ListContainers. +type ContainerProperties struct { + LastModified string `xml:"Last-Modified"` + Etag string `xml:"Etag"` + LeaseStatus string `xml:"LeaseStatus"` + LeaseState string `xml:"LeaseState"` + LeaseDuration string `xml:"LeaseDuration"` +} + +// ContainerListResponse contains the response fields from +// ListContainers call. +// +// See https://msdn.microsoft.com/en-us/library/azure/dd179352.aspx +type ContainerListResponse struct { + XMLName xml.Name `xml:"EnumerationResults"` + Xmlns string `xml:"xmlns,attr"` + Prefix string `xml:"Prefix"` + Marker string `xml:"Marker"` + NextMarker string `xml:"NextMarker"` + MaxResults int64 `xml:"MaxResults"` + Containers []Container `xml:"Containers>Container"` +} + +// BlobListResponse contains the response fields from ListBlobs call. +// +// See https://msdn.microsoft.com/en-us/library/azure/dd135734.aspx +type BlobListResponse struct { + XMLName xml.Name `xml:"EnumerationResults"` + Xmlns string `xml:"xmlns,attr"` + Prefix string `xml:"Prefix"` + Marker string `xml:"Marker"` + 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"` +} + +// IncludeBlobDataset has options to include in a list blobs operation +type IncludeBlobDataset struct { + Snapshots bool + Metadata bool + UncommittedBlobs bool + Copy bool +} + +// ListBlobsParameters defines the set of customizable +// parameters to make a List Blobs call. +// +// See https://msdn.microsoft.com/en-us/library/azure/dd135734.aspx +type ListBlobsParameters struct { + Prefix string + Delimiter string + Marker string + Include *IncludeBlobDataset + MaxResults uint + Timeout uint + RequestID string +} + +func (p ListBlobsParameters) getParameters() url.Values { + out := url.Values{} + + if p.Prefix != "" { + out.Set("prefix", p.Prefix) + } + if p.Delimiter != "" { + out.Set("delimiter", p.Delimiter) + } + if p.Marker != "" { + out.Set("marker", p.Marker) + } + if p.Include != nil { + include := []string{} + include = addString(include, p.Include.Snapshots, "snapshots") + include = addString(include, p.Include.Metadata, "metadata") + include = addString(include, p.Include.UncommittedBlobs, "uncommittedblobs") + include = addString(include, p.Include.Copy, "copy") + fullInclude := strings.Join(include, ",") + out.Set("include", fullInclude) + } + if p.MaxResults != 0 { + out.Set("maxresults", strconv.FormatUint(uint64(p.MaxResults), 10)) + } + if p.Timeout != 0 { + out.Set("timeout", strconv.FormatUint(uint64(p.Timeout), 10)) + } + + return out +} + +func addString(datasets []string, include bool, text string) []string { + if include { + datasets = append(datasets, text) + } + return datasets +} + +// ContainerAccessType defines the access level to the container from a public +// request. +// +// See https://msdn.microsoft.com/en-us/library/azure/dd179468.aspx and "x-ms- +// blob-public-access" header. +type ContainerAccessType string + +// Access options for containers +const ( + ContainerAccessTypePrivate ContainerAccessType = "" + ContainerAccessTypeBlob ContainerAccessType = "blob" + ContainerAccessTypeContainer ContainerAccessType = "container" +) + +// ContainerAccessPolicy represents each access policy in the container ACL. +type ContainerAccessPolicy struct { + ID string + StartTime time.Time + ExpiryTime time.Time + CanRead bool + CanWrite bool + CanDelete bool +} + +// ContainerPermissions represents the container ACLs. +type ContainerPermissions struct { + AccessType ContainerAccessType + AccessPolicies []ContainerAccessPolicy +} + +// ContainerAccessHeader references header used when setting/getting container ACL +const ( + ContainerAccessHeader string = "x-ms-blob-public-access" +) + +// GetBlobReference returns a Blob object for the specified blob name. +func (c *Container) GetBlobReference(name string) *Blob { + return &Blob{ + Container: c, + Name: name, + } +} + +// CreateContainerOptions includes the options for a create container operation +type CreateContainerOptions struct { + Timeout uint + Access ContainerAccessType `header:"x-ms-blob-public-access"` + RequestID string `header:"x-ms-client-request-id"` +} + +// Create creates a blob container within the storage account +// with given name and access level. Returns error if container already exists. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Create-Container +func (c *Container) Create(options *CreateContainerOptions) error { + resp, err := c.create(options) + if err != nil { + return err + } + readAndCloseBody(resp.body) + return checkRespCode(resp.statusCode, []int{http.StatusCreated}) +} + +// CreateIfNotExists creates a blob container if it does not exist. Returns +// true if container is newly created or false if container already exists. +func (c *Container) CreateIfNotExists(options *CreateContainerOptions) (bool, error) { + resp, err := c.create(options) + if resp != nil { + defer readAndCloseBody(resp.body) + if resp.statusCode == http.StatusCreated || resp.statusCode == http.StatusConflict { + return resp.statusCode == http.StatusCreated, nil + } + } + return false, err +} + +func (c *Container) create(options *CreateContainerOptions) (*storageResponse, error) { + query := url.Values{"restype": {"container"}} + headers := c.bsc.client.getStandardHeaders() + headers = c.bsc.client.addMetadataToHeaders(headers, c.Metadata) + + if options != nil { + query = addTimeout(query, options.Timeout) + headers = mergeHeaders(headers, headersFromStruct(*options)) + } + uri := c.bsc.client.getEndpoint(blobServiceName, c.buildPath(), query) + + return c.bsc.client.exec(http.MethodPut, uri, headers, nil, c.bsc.auth) +} + +// Exists returns true if a container with given name exists +// on the storage account, otherwise returns false. +func (c *Container) Exists() (bool, error) { + uri := c.bsc.client.getEndpoint(blobServiceName, c.buildPath(), url.Values{"restype": {"container"}}) + headers := c.bsc.client.getStandardHeaders() + + resp, err := c.bsc.client.exec(http.MethodHead, uri, headers, nil, c.bsc.auth) + if resp != nil { + defer readAndCloseBody(resp.body) + if resp.statusCode == http.StatusOK || resp.statusCode == http.StatusNotFound { + return resp.statusCode == http.StatusOK, nil + } + } + return false, err +} + +// SetContainerPermissionOptions includes options for a set container permissions operation +type SetContainerPermissionOptions struct { + Timeout uint + LeaseID string `header:"x-ms-lease-id"` + IfModifiedSince *time.Time `header:"If-Modified-Since"` + IfUnmodifiedSince *time.Time `header:"If-Unmodified-Since"` + RequestID string `header:"x-ms-client-request-id"` +} + +// SetPermissions sets up container permissions +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Set-Container-ACL +func (c *Container) SetPermissions(permissions ContainerPermissions, options *SetContainerPermissionOptions) error { + body, length, err := generateContainerACLpayload(permissions.AccessPolicies) + if err != nil { + return err + } + params := url.Values{ + "restype": {"container"}, + "comp": {"acl"}, + } + headers := c.bsc.client.getStandardHeaders() + headers = addToHeaders(headers, ContainerAccessHeader, string(permissions.AccessType)) + headers["Content-Length"] = strconv.Itoa(length) + + if options != nil { + params = addTimeout(params, options.Timeout) + headers = mergeHeaders(headers, headersFromStruct(*options)) + } + uri := c.bsc.client.getEndpoint(blobServiceName, c.buildPath(), params) + + resp, err := c.bsc.client.exec(http.MethodPut, uri, headers, body, c.bsc.auth) + if err != nil { + return err + } + defer readAndCloseBody(resp.body) + + if err := checkRespCode(resp.statusCode, []int{http.StatusOK}); err != nil { + return errors.New("Unable to set permissions") + } + + return nil +} + +// GetContainerPermissionOptions includes options for a get container permissions operation +type GetContainerPermissionOptions struct { + Timeout uint + LeaseID string `header:"x-ms-lease-id"` + RequestID string `header:"x-ms-client-request-id"` +} + +// GetPermissions gets the container permissions as per https://msdn.microsoft.com/en-us/library/azure/dd179469.aspx +// If timeout is 0 then it will not be passed to Azure +// leaseID will only be passed to Azure if populated +func (c *Container) GetPermissions(options *GetContainerPermissionOptions) (*ContainerPermissions, error) { + params := url.Values{ + "restype": {"container"}, + "comp": {"acl"}, + } + headers := c.bsc.client.getStandardHeaders() + + if options != nil { + params = addTimeout(params, options.Timeout) + headers = mergeHeaders(headers, headersFromStruct(*options)) + } + uri := c.bsc.client.getEndpoint(blobServiceName, c.buildPath(), params) + + resp, err := c.bsc.client.exec(http.MethodGet, uri, headers, nil, c.bsc.auth) + if err != nil { + return nil, err + } + defer resp.body.Close() + + var ap AccessPolicy + err = xmlUnmarshal(resp.body, &ap.SignedIdentifiersList) + if err != nil { + return nil, err + } + return buildAccessPolicy(ap, &resp.headers), nil +} + +func buildAccessPolicy(ap AccessPolicy, headers *http.Header) *ContainerPermissions { + // containerAccess. Blob, Container, empty + containerAccess := headers.Get(http.CanonicalHeaderKey(ContainerAccessHeader)) + permissions := ContainerPermissions{ + AccessType: ContainerAccessType(containerAccess), + AccessPolicies: []ContainerAccessPolicy{}, + } + + for _, policy := range ap.SignedIdentifiersList.SignedIdentifiers { + capd := ContainerAccessPolicy{ + ID: policy.ID, + StartTime: policy.AccessPolicy.StartTime, + ExpiryTime: policy.AccessPolicy.ExpiryTime, + } + capd.CanRead = updatePermissions(policy.AccessPolicy.Permission, "r") + capd.CanWrite = updatePermissions(policy.AccessPolicy.Permission, "w") + capd.CanDelete = updatePermissions(policy.AccessPolicy.Permission, "d") + + permissions.AccessPolicies = append(permissions.AccessPolicies, capd) + } + return &permissions +} + +// DeleteContainerOptions includes options for a delete container operation +type DeleteContainerOptions struct { + Timeout uint + LeaseID string `header:"x-ms-lease-id"` + IfModifiedSince *time.Time `header:"If-Modified-Since"` + IfUnmodifiedSince *time.Time `header:"If-Unmodified-Since"` + RequestID string `header:"x-ms-client-request-id"` +} + +// Delete deletes the container with given name on the storage +// account. If the container does not exist returns error. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/delete-container +func (c *Container) Delete(options *DeleteContainerOptions) error { + resp, err := c.delete(options) + if err != nil { + return err + } + readAndCloseBody(resp.body) + return checkRespCode(resp.statusCode, []int{http.StatusAccepted}) +} + +// DeleteIfExists deletes the container with given name on the storage +// account if it exists. Returns true if container is deleted with this call, or +// false if the container did not exist at the time of the Delete Container +// operation. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/delete-container +func (c *Container) DeleteIfExists(options *DeleteContainerOptions) (bool, error) { + resp, err := c.delete(options) + if resp != nil { + defer readAndCloseBody(resp.body) + if resp.statusCode == http.StatusAccepted || resp.statusCode == http.StatusNotFound { + return resp.statusCode == http.StatusAccepted, nil + } + } + return false, err +} + +func (c *Container) delete(options *DeleteContainerOptions) (*storageResponse, error) { + query := url.Values{"restype": {"container"}} + headers := c.bsc.client.getStandardHeaders() + + if options != nil { + query = addTimeout(query, options.Timeout) + headers = mergeHeaders(headers, headersFromStruct(*options)) + } + uri := c.bsc.client.getEndpoint(blobServiceName, c.buildPath(), query) + + return c.bsc.client.exec(http.MethodDelete, uri, headers, nil, c.bsc.auth) +} + +// ListBlobs returns an object that contains list of blobs in the container, +// pagination token and other information in the response of List Blobs call. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/List-Blobs +func (c *Container) ListBlobs(params ListBlobsParameters) (BlobListResponse, error) { + q := mergeParams(params.getParameters(), url.Values{ + "restype": {"container"}, + "comp": {"list"}}, + ) + uri := c.bsc.client.getEndpoint(blobServiceName, c.buildPath(), q) + + headers := c.bsc.client.getStandardHeaders() + headers = addToHeaders(headers, "x-ms-client-request-id", params.RequestID) + + var out BlobListResponse + resp, err := c.bsc.client.exec(http.MethodGet, uri, headers, nil, c.bsc.auth) + if err != nil { + return out, err + } + defer resp.body.Close() + + err = xmlUnmarshal(resp.body, &out) + for i := range out.Blobs { + out.Blobs[i].Container = c + } + return out, err +} + +func generateContainerACLpayload(policies []ContainerAccessPolicy) (io.Reader, int, error) { + sil := SignedIdentifiers{ + SignedIdentifiers: []SignedIdentifier{}, + } + for _, capd := range policies { + permission := capd.generateContainerPermissions() + signedIdentifier := convertAccessPolicyToXMLStructs(capd.ID, capd.StartTime, capd.ExpiryTime, permission) + sil.SignedIdentifiers = append(sil.SignedIdentifiers, signedIdentifier) + } + return xmlMarshal(sil) +} + +func (capd *ContainerAccessPolicy) generateContainerPermissions() (permissions string) { + // generate the permissions string (rwd). + // still want the end user API to have bool flags. + permissions = "" + + if capd.CanRead { + permissions += "r" + } + + if capd.CanWrite { + permissions += "w" + } + + if capd.CanDelete { + permissions += "d" + } + + return permissions +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/copyblob.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/copyblob.go new file mode 100644 index 000000000000..377a3c622e9a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/copyblob.go @@ -0,0 +1,223 @@ +package storage + +import ( + "errors" + "fmt" + "net/http" + "net/url" + "strings" + "time" +) + +const ( + blobCopyStatusPending = "pending" + blobCopyStatusSuccess = "success" + blobCopyStatusAborted = "aborted" + blobCopyStatusFailed = "failed" +) + +// CopyOptions includes the options for a copy blob operation +type CopyOptions struct { + Timeout uint + Source CopyOptionsConditions + Destiny CopyOptionsConditions + RequestID string +} + +// IncrementalCopyOptions includes the options for an incremental copy blob operation +type IncrementalCopyOptions struct { + Timeout uint + Destination IncrementalCopyOptionsConditions + RequestID string +} + +// CopyOptionsConditions includes some conditional options in a copy blob operation +type CopyOptionsConditions struct { + LeaseID string + IfModifiedSince *time.Time + IfUnmodifiedSince *time.Time + IfMatch string + IfNoneMatch string +} + +// IncrementalCopyOptionsConditions includes some conditional options in a copy blob operation +type IncrementalCopyOptionsConditions struct { + IfModifiedSince *time.Time + IfUnmodifiedSince *time.Time + IfMatch string + IfNoneMatch string +} + +// Copy 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 +// this helper method works faster on smaller files. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Copy-Blob +func (b *Blob) Copy(sourceBlob string, options *CopyOptions) error { + copyID, err := b.StartCopy(sourceBlob, options) + if err != nil { + return err + } + + return b.WaitForCopy(copyID) +} + +// StartCopy starts a blob copy operation. +// sourceBlob parameter must be a canonical URL to the blob (can be +// obtained using GetBlobURL method.) +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Copy-Blob +func (b *Blob) StartCopy(sourceBlob string, options *CopyOptions) (string, error) { + params := url.Values{} + headers := b.Container.bsc.client.getStandardHeaders() + headers["x-ms-copy-source"] = sourceBlob + headers = b.Container.bsc.client.addMetadataToHeaders(headers, b.Metadata) + + if options != nil { + params = addTimeout(params, options.Timeout) + headers = addToHeaders(headers, "x-ms-client-request-id", options.RequestID) + // source + headers = addToHeaders(headers, "x-ms-source-lease-id", options.Source.LeaseID) + headers = addTimeToHeaders(headers, "x-ms-source-if-modified-since", options.Source.IfModifiedSince) + headers = addTimeToHeaders(headers, "x-ms-source-if-unmodified-since", options.Source.IfUnmodifiedSince) + headers = addToHeaders(headers, "x-ms-source-if-match", options.Source.IfMatch) + headers = addToHeaders(headers, "x-ms-source-if-none-match", options.Source.IfNoneMatch) + //destiny + headers = addToHeaders(headers, "x-ms-lease-id", options.Destiny.LeaseID) + headers = addTimeToHeaders(headers, "x-ms-if-modified-since", options.Destiny.IfModifiedSince) + headers = addTimeToHeaders(headers, "x-ms-if-unmodified-since", options.Destiny.IfUnmodifiedSince) + headers = addToHeaders(headers, "x-ms-if-match", options.Destiny.IfMatch) + headers = addToHeaders(headers, "x-ms-if-none-match", options.Destiny.IfNoneMatch) + } + uri := b.Container.bsc.client.getEndpoint(blobServiceName, b.buildPath(), params) + + resp, err := b.Container.bsc.client.exec(http.MethodPut, uri, headers, nil, b.Container.bsc.auth) + if err != nil { + return "", err + } + defer readAndCloseBody(resp.body) + + if err := checkRespCode(resp.statusCode, []int{http.StatusAccepted, http.StatusCreated}); err != nil { + return "", err + } + + copyID := resp.headers.Get("x-ms-copy-id") + if copyID == "" { + return "", errors.New("Got empty copy id header") + } + return copyID, nil +} + +// AbortCopyOptions includes the options for an abort blob operation +type AbortCopyOptions struct { + Timeout uint + LeaseID string `header:"x-ms-lease-id"` + RequestID string `header:"x-ms-client-request-id"` +} + +// AbortCopy aborts a BlobCopy which has already been triggered by the StartBlobCopy function. +// copyID is generated from StartBlobCopy function. +// currentLeaseID is required IF the destination blob has an active lease on it. +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Abort-Copy-Blob +func (b *Blob) AbortCopy(copyID string, options *AbortCopyOptions) error { + params := url.Values{ + "comp": {"copy"}, + "copyid": {copyID}, + } + headers := b.Container.bsc.client.getStandardHeaders() + headers["x-ms-copy-action"] = "abort" + + if options != nil { + params = addTimeout(params, options.Timeout) + headers = mergeHeaders(headers, headersFromStruct(*options)) + } + uri := b.Container.bsc.client.getEndpoint(blobServiceName, b.buildPath(), params) + + resp, err := b.Container.bsc.client.exec(http.MethodPut, uri, headers, nil, b.Container.bsc.auth) + if err != nil { + return err + } + readAndCloseBody(resp.body) + return checkRespCode(resp.statusCode, []int{http.StatusNoContent}) +} + +// WaitForCopy loops until a BlobCopy operation is completed (or fails with error) +func (b *Blob) WaitForCopy(copyID string) error { + for { + err := b.GetProperties(nil) + if err != nil { + return err + } + + if b.Properties.CopyID != copyID { + return errBlobCopyIDMismatch + } + + switch b.Properties.CopyStatus { + case blobCopyStatusSuccess: + return nil + case blobCopyStatusPending: + continue + case blobCopyStatusAborted: + return errBlobCopyAborted + case blobCopyStatusFailed: + return fmt.Errorf("storage: blob copy failed. Id=%s Description=%s", b.Properties.CopyID, b.Properties.CopyStatusDescription) + default: + return fmt.Errorf("storage: unhandled blob copy status: '%s'", b.Properties.CopyStatus) + } + } +} + +// IncrementalCopyBlob copies a snapshot of a source blob and copies to referring blob +// sourceBlob parameter must be a valid snapshot URL of the original blob. +// THe original blob mut be public, or use a Shared Access Signature. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/incremental-copy-blob . +func (b *Blob) IncrementalCopyBlob(sourceBlobURL string, snapshotTime time.Time, options *IncrementalCopyOptions) (string, error) { + params := url.Values{"comp": {"incrementalcopy"}} + + // need formatting to 7 decimal places so it's friendly to Windows and *nix + snapshotTimeFormatted := snapshotTime.Format("2006-01-02T15:04:05.0000000Z") + u, err := url.Parse(sourceBlobURL) + if err != nil { + return "", err + } + query := u.Query() + query.Add("snapshot", snapshotTimeFormatted) + encodedQuery := query.Encode() + encodedQuery = strings.Replace(encodedQuery, "%3A", ":", -1) + u.RawQuery = encodedQuery + snapshotURL := u.String() + + headers := b.Container.bsc.client.getStandardHeaders() + headers["x-ms-copy-source"] = snapshotURL + + if options != nil { + addTimeout(params, options.Timeout) + headers = addToHeaders(headers, "x-ms-client-request-id", options.RequestID) + headers = addTimeToHeaders(headers, "x-ms-if-modified-since", options.Destination.IfModifiedSince) + headers = addTimeToHeaders(headers, "x-ms-if-unmodified-since", options.Destination.IfUnmodifiedSince) + headers = addToHeaders(headers, "x-ms-if-match", options.Destination.IfMatch) + headers = addToHeaders(headers, "x-ms-if-none-match", options.Destination.IfNoneMatch) + } + + // get URI of destination blob + uri := b.Container.bsc.client.getEndpoint(blobServiceName, b.buildPath(), params) + + resp, err := b.Container.bsc.client.exec(http.MethodPut, uri, headers, nil, b.Container.bsc.auth) + if err != nil { + return "", err + } + defer readAndCloseBody(resp.body) + + if err := checkRespCode(resp.statusCode, []int{http.StatusAccepted}); err != nil { + return "", err + } + + copyID := resp.headers.Get("x-ms-copy-id") + if copyID == "" { + return "", errors.New("Got empty copy id header") + } + return copyID, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/directory.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/directory.go new file mode 100644 index 000000000000..29610329ec31 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/directory.go @@ -0,0 +1,222 @@ +package storage + +import ( + "encoding/xml" + "net/http" + "net/url" +) + +// Directory represents a directory on a share. +type Directory struct { + fsc *FileServiceClient + Metadata map[string]string + Name string `xml:"Name"` + parent *Directory + Properties DirectoryProperties + share *Share +} + +// DirectoryProperties contains various properties of a directory. +type DirectoryProperties struct { + LastModified string `xml:"Last-Modified"` + Etag string `xml:"Etag"` +} + +// ListDirsAndFilesParameters defines the set of customizable parameters to +// make a List Files and Directories call. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/List-Directories-and-Files +type ListDirsAndFilesParameters struct { + Prefix string + Marker string + MaxResults uint + Timeout uint +} + +// DirsAndFilesListResponse contains the response fields from +// a List Files and Directories call. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/List-Directories-and-Files +type DirsAndFilesListResponse struct { + XMLName xml.Name `xml:"EnumerationResults"` + Xmlns string `xml:"xmlns,attr"` + Marker string `xml:"Marker"` + MaxResults int64 `xml:"MaxResults"` + Directories []Directory `xml:"Entries>Directory"` + Files []File `xml:"Entries>File"` + NextMarker string `xml:"NextMarker"` +} + +// builds the complete directory path for this directory object. +func (d *Directory) buildPath() string { + path := "" + current := d + for current.Name != "" { + path = "/" + current.Name + path + current = current.parent + } + return d.share.buildPath() + path +} + +// Create this directory in the associated share. +// If a directory with the same name already exists, the operation fails. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Create-Directory +func (d *Directory) Create(options *FileRequestOptions) error { + // if this is the root directory exit early + if d.parent == nil { + return nil + } + + params := prepareOptions(options) + headers, err := d.fsc.createResource(d.buildPath(), resourceDirectory, params, mergeMDIntoExtraHeaders(d.Metadata, nil), []int{http.StatusCreated}) + if err != nil { + return err + } + + d.updateEtagAndLastModified(headers) + return nil +} + +// CreateIfNotExists creates this directory under the associated share if the +// directory does not exists. Returns true if the directory is newly created or +// false if the directory already exists. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Create-Directory +func (d *Directory) CreateIfNotExists(options *FileRequestOptions) (bool, error) { + // if this is the root directory exit early + if d.parent == nil { + return false, nil + } + + params := prepareOptions(options) + resp, err := d.fsc.createResourceNoClose(d.buildPath(), resourceDirectory, params, nil) + if resp != nil { + defer readAndCloseBody(resp.body) + if resp.statusCode == http.StatusCreated || resp.statusCode == http.StatusConflict { + if resp.statusCode == http.StatusCreated { + d.updateEtagAndLastModified(resp.headers) + return true, nil + } + + return false, d.FetchAttributes(nil) + } + } + + return false, err +} + +// Delete removes this directory. It must be empty in order to be deleted. +// If the directory does not exist the operation fails. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Delete-Directory +func (d *Directory) Delete(options *FileRequestOptions) error { + return d.fsc.deleteResource(d.buildPath(), resourceDirectory, options) +} + +// DeleteIfExists removes this directory if it exists. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Delete-Directory +func (d *Directory) DeleteIfExists(options *FileRequestOptions) (bool, error) { + resp, err := d.fsc.deleteResourceNoClose(d.buildPath(), resourceDirectory, options) + if resp != nil { + defer readAndCloseBody(resp.body) + if resp.statusCode == http.StatusAccepted || resp.statusCode == http.StatusNotFound { + return resp.statusCode == http.StatusAccepted, nil + } + } + return false, err +} + +// Exists returns true if this directory exists. +func (d *Directory) Exists() (bool, error) { + exists, headers, err := d.fsc.resourceExists(d.buildPath(), resourceDirectory) + if exists { + d.updateEtagAndLastModified(headers) + } + return exists, err +} + +// FetchAttributes retrieves metadata for this directory. +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/get-directory-properties +func (d *Directory) FetchAttributes(options *FileRequestOptions) error { + params := prepareOptions(options) + headers, err := d.fsc.getResourceHeaders(d.buildPath(), compNone, resourceDirectory, params, http.MethodHead) + if err != nil { + return err + } + + d.updateEtagAndLastModified(headers) + d.Metadata = getMetadataFromHeaders(headers) + + return nil +} + +// GetDirectoryReference returns a child Directory object for this directory. +func (d *Directory) GetDirectoryReference(name string) *Directory { + return &Directory{ + fsc: d.fsc, + Name: name, + parent: d, + share: d.share, + } +} + +// GetFileReference returns a child File object for this directory. +func (d *Directory) GetFileReference(name string) *File { + return &File{ + fsc: d.fsc, + Name: name, + parent: d, + share: d.share, + } +} + +// ListDirsAndFiles returns a list of files and directories under this directory. +// It also contains a pagination token and other response details. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/List-Directories-and-Files +func (d *Directory) ListDirsAndFiles(params ListDirsAndFilesParameters) (*DirsAndFilesListResponse, error) { + q := mergeParams(params.getParameters(), getURLInitValues(compList, resourceDirectory)) + + resp, err := d.fsc.listContent(d.buildPath(), q, nil) + if err != nil { + return nil, err + } + + defer resp.body.Close() + var out DirsAndFilesListResponse + err = xmlUnmarshal(resp.body, &out) + return &out, err +} + +// SetMetadata replaces the metadata for this directory. +// +// Some keys may be converted to Camel-Case before sending. All keys +// are returned in lower case by GetDirectoryMetadata. HTTP header names +// are case-insensitive so case munging should not matter to other +// applications either. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Set-Directory-Metadata +func (d *Directory) SetMetadata(options *FileRequestOptions) error { + headers, err := d.fsc.setResourceHeaders(d.buildPath(), compMetadata, resourceDirectory, mergeMDIntoExtraHeaders(d.Metadata, nil), options) + if err != nil { + return err + } + + d.updateEtagAndLastModified(headers) + return nil +} + +// updates Etag and last modified date +func (d *Directory) updateEtagAndLastModified(headers http.Header) { + d.Properties.Etag = headers.Get("Etag") + d.Properties.LastModified = headers.Get("Last-Modified") +} + +// URL gets the canonical URL to this directory. +// This method does not create a publicly accessible URL if the directory +// is private and this method does not check if the directory exists. +func (d *Directory) URL() string { + return d.fsc.client.getEndpoint(fileServiceName, d.buildPath(), url.Values{}) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/entity.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/entity.go new file mode 100644 index 000000000000..13e94750731f --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/entity.go @@ -0,0 +1,439 @@ +package storage + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io/ioutil" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "github.com/satori/uuid" +) + +// Annotating as secure for gas scanning +/* #nosec */ +const ( + partitionKeyNode = "PartitionKey" + rowKeyNode = "RowKey" + etagErrorTemplate = "Etag didn't match: %v" +) + +var ( + errEmptyPayload = errors.New("Empty payload is not a valid metadata level for this operation") + errNilPreviousResult = errors.New("The previous results page is nil") + errNilNextLink = errors.New("There are no more pages in this query results") +) + +// Entity represents an entity inside an Azure table. +type Entity struct { + Table *Table + PartitionKey string + RowKey string + TimeStamp time.Time + OdataMetadata string + OdataType string + OdataID string + OdataEtag string + OdataEditLink string + Properties map[string]interface{} +} + +// GetEntityReference returns an Entity object with the specified +// partition key and row key. +func (t *Table) GetEntityReference(partitionKey, rowKey string) *Entity { + return &Entity{ + PartitionKey: partitionKey, + RowKey: rowKey, + Table: t, + } +} + +// EntityOptions includes options for entity operations. +type EntityOptions struct { + Timeout uint + RequestID string `header:"x-ms-client-request-id"` +} + +// GetEntityOptions includes options for a get entity operation +type GetEntityOptions struct { + Select []string + RequestID string `header:"x-ms-client-request-id"` +} + +// Get gets the referenced entity. Which properties to get can be +// specified using the select option. +// See: +// https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/query-entities +// https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/querying-tables-and-entities +func (e *Entity) Get(timeout uint, ml MetadataLevel, options *GetEntityOptions) error { + if ml == EmptyPayload { + return errEmptyPayload + } + // RowKey and PartitionKey could be lost if not included in the query + // As those are the entity identifiers, it is best if they are not lost + rk := e.RowKey + pk := e.PartitionKey + + query := url.Values{ + "timeout": {strconv.FormatUint(uint64(timeout), 10)}, + } + headers := e.Table.tsc.client.getStandardHeaders() + headers[headerAccept] = string(ml) + + if options != nil { + if len(options.Select) > 0 { + query.Add("$select", strings.Join(options.Select, ",")) + } + headers = mergeHeaders(headers, headersFromStruct(*options)) + } + + uri := e.Table.tsc.client.getEndpoint(tableServiceName, e.buildPath(), query) + resp, err := e.Table.tsc.client.exec(http.MethodGet, uri, headers, nil, e.Table.tsc.auth) + if err != nil { + return err + } + defer readAndCloseBody(resp.body) + + if err = checkRespCode(resp.statusCode, []int{http.StatusOK}); err != nil { + return err + } + + respBody, err := ioutil.ReadAll(resp.body) + if err != nil { + return err + } + err = json.Unmarshal(respBody, e) + if err != nil { + return err + } + e.PartitionKey = pk + e.RowKey = rk + + return nil +} + +// Insert inserts the referenced entity in its table. +// The function fails if there is an entity with the same +// PartitionKey and RowKey in the table. +// ml determines the level of detail of metadata in the operation response, +// or no data at all. +// See: https://docs.microsoft.com/rest/api/storageservices/fileservices/insert-entity +func (e *Entity) Insert(ml MetadataLevel, options *EntityOptions) error { + query, headers := options.getParameters() + headers = mergeHeaders(headers, e.Table.tsc.client.getStandardHeaders()) + + body, err := json.Marshal(e) + if err != nil { + return err + } + headers = addBodyRelatedHeaders(headers, len(body)) + headers = addReturnContentHeaders(headers, ml) + + uri := e.Table.tsc.client.getEndpoint(tableServiceName, e.Table.buildPath(), query) + resp, err := e.Table.tsc.client.exec(http.MethodPost, uri, headers, bytes.NewReader(body), e.Table.tsc.auth) + if err != nil { + return err + } + defer resp.body.Close() + + data, err := ioutil.ReadAll(resp.body) + if err != nil { + return err + } + + if ml != EmptyPayload { + if err = checkRespCode(resp.statusCode, []int{http.StatusCreated}); err != nil { + return err + } + if err = e.UnmarshalJSON(data); err != nil { + return err + } + } else { + if err = checkRespCode(resp.statusCode, []int{http.StatusNoContent}); err != nil { + return err + } + } + + return nil +} + +// Update updates the contents of an entity. The function fails if there is no entity +// with the same PartitionKey and RowKey in the table or if the ETag is different +// than the one in Azure. +// See: https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/update-entity2 +func (e *Entity) Update(force bool, options *EntityOptions) error { + return e.updateMerge(force, http.MethodPut, options) +} + +// Merge merges the contents of entity specified with PartitionKey and RowKey +// with the content specified in Properties. +// The function fails if there is no entity with the same PartitionKey and +// RowKey in the table or if the ETag is different than the one in Azure. +// Read more: https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/merge-entity +func (e *Entity) Merge(force bool, options *EntityOptions) error { + return e.updateMerge(force, "MERGE", options) +} + +// Delete deletes the entity. +// The function fails if there is no entity with the same PartitionKey and +// RowKey in the table or if the ETag is different than the one in Azure. +// See: https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/delete-entity1 +func (e *Entity) Delete(force bool, options *EntityOptions) error { + query, headers := options.getParameters() + headers = mergeHeaders(headers, e.Table.tsc.client.getStandardHeaders()) + + headers = addIfMatchHeader(headers, force, e.OdataEtag) + headers = addReturnContentHeaders(headers, EmptyPayload) + + uri := e.Table.tsc.client.getEndpoint(tableServiceName, e.buildPath(), query) + resp, err := e.Table.tsc.client.exec(http.MethodDelete, uri, headers, nil, e.Table.tsc.auth) + if err != nil { + if resp.statusCode == http.StatusPreconditionFailed { + return fmt.Errorf(etagErrorTemplate, err) + } + return err + } + defer readAndCloseBody(resp.body) + + if err = checkRespCode(resp.statusCode, []int{http.StatusNoContent}); err != nil { + return err + } + + return e.updateTimestamp(resp.headers) +} + +// InsertOrReplace inserts an entity or replaces the existing one. +// Read more: https://docs.microsoft.com/rest/api/storageservices/fileservices/insert-or-replace-entity +func (e *Entity) InsertOrReplace(options *EntityOptions) error { + return e.insertOr(http.MethodPut, options) +} + +// InsertOrMerge inserts an entity or merges the existing one. +// Read more: https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/insert-or-merge-entity +func (e *Entity) InsertOrMerge(options *EntityOptions) error { + return e.insertOr("MERGE", options) +} + +func (e *Entity) buildPath() string { + return fmt.Sprintf("%s(PartitionKey='%s', RowKey='%s')", e.Table.buildPath(), e.PartitionKey, e.RowKey) +} + +// MarshalJSON is a custom marshaller for entity +func (e *Entity) MarshalJSON() ([]byte, error) { + completeMap := map[string]interface{}{} + completeMap[partitionKeyNode] = e.PartitionKey + completeMap[rowKeyNode] = e.RowKey + for k, v := range e.Properties { + typeKey := strings.Join([]string{k, OdataTypeSuffix}, "") + switch t := v.(type) { + case []byte: + completeMap[typeKey] = OdataBinary + completeMap[k] = string(t) + case time.Time: + completeMap[typeKey] = OdataDateTime + completeMap[k] = t.Format(time.RFC3339Nano) + case uuid.UUID: + completeMap[typeKey] = OdataGUID + completeMap[k] = t.String() + case int64: + completeMap[typeKey] = OdataInt64 + completeMap[k] = fmt.Sprintf("%v", v) + default: + completeMap[k] = v + } + if strings.HasSuffix(k, OdataTypeSuffix) { + if !(completeMap[k] == OdataBinary || + completeMap[k] == OdataDateTime || + completeMap[k] == OdataGUID || + completeMap[k] == OdataInt64) { + return nil, fmt.Errorf("Odata.type annotation %v value is not valid", k) + } + valueKey := strings.TrimSuffix(k, OdataTypeSuffix) + if _, ok := completeMap[valueKey]; !ok { + return nil, fmt.Errorf("Odata.type annotation %v defined without value defined", k) + } + } + } + return json.Marshal(completeMap) +} + +// UnmarshalJSON is a custom unmarshaller for entities +func (e *Entity) UnmarshalJSON(data []byte) error { + errorTemplate := "Deserializing error: %v" + + props := map[string]interface{}{} + err := json.Unmarshal(data, &props) + if err != nil { + return err + } + + // deselialize metadata + e.OdataMetadata = stringFromMap(props, "odata.metadata") + e.OdataType = stringFromMap(props, "odata.type") + e.OdataID = stringFromMap(props, "odata.id") + e.OdataEtag = stringFromMap(props, "odata.etag") + e.OdataEditLink = stringFromMap(props, "odata.editLink") + e.PartitionKey = stringFromMap(props, partitionKeyNode) + e.RowKey = stringFromMap(props, rowKeyNode) + + // deserialize timestamp + timeStamp, ok := props["Timestamp"] + if ok { + str, ok := timeStamp.(string) + if !ok { + return fmt.Errorf(errorTemplate, "Timestamp casting error") + } + t, err := time.Parse(time.RFC3339Nano, str) + if err != nil { + return fmt.Errorf(errorTemplate, err) + } + e.TimeStamp = t + } + delete(props, "Timestamp") + delete(props, "Timestamp@odata.type") + + // deserialize entity (user defined fields) + for k, v := range props { + if strings.HasSuffix(k, OdataTypeSuffix) { + valueKey := strings.TrimSuffix(k, OdataTypeSuffix) + str, ok := props[valueKey].(string) + if !ok { + return fmt.Errorf(errorTemplate, fmt.Sprintf("%v casting error", v)) + } + switch v { + case OdataBinary: + props[valueKey] = []byte(str) + case OdataDateTime: + t, err := time.Parse("2006-01-02T15:04:05Z", str) + if err != nil { + return fmt.Errorf(errorTemplate, err) + } + props[valueKey] = t + case OdataGUID: + props[valueKey] = uuid.FromStringOrNil(str) + case OdataInt64: + i, err := strconv.ParseInt(str, 10, 64) + if err != nil { + return fmt.Errorf(errorTemplate, err) + } + props[valueKey] = i + default: + return fmt.Errorf(errorTemplate, fmt.Sprintf("%v is not supported", v)) + } + delete(props, k) + } + } + + e.Properties = props + return nil +} + +func getAndDelete(props map[string]interface{}, key string) interface{} { + if value, ok := props[key]; ok { + delete(props, key) + return value + } + return nil +} + +func addIfMatchHeader(h map[string]string, force bool, etag string) map[string]string { + if force { + h[headerIfMatch] = "*" + } else { + h[headerIfMatch] = etag + } + return h +} + +// updates Etag and timestamp +func (e *Entity) updateEtagAndTimestamp(headers http.Header) error { + e.OdataEtag = headers.Get(headerEtag) + return e.updateTimestamp(headers) +} + +func (e *Entity) updateTimestamp(headers http.Header) error { + str := headers.Get(headerDate) + t, err := time.Parse(time.RFC1123, str) + if err != nil { + return fmt.Errorf("Update timestamp error: %v", err) + } + e.TimeStamp = t + return nil +} + +func (e *Entity) insertOr(verb string, options *EntityOptions) error { + query, headers := options.getParameters() + headers = mergeHeaders(headers, e.Table.tsc.client.getStandardHeaders()) + + body, err := json.Marshal(e) + if err != nil { + return err + } + headers = addBodyRelatedHeaders(headers, len(body)) + headers = addReturnContentHeaders(headers, EmptyPayload) + + uri := e.Table.tsc.client.getEndpoint(tableServiceName, e.buildPath(), query) + resp, err := e.Table.tsc.client.exec(verb, uri, headers, bytes.NewReader(body), e.Table.tsc.auth) + if err != nil { + return err + } + defer readAndCloseBody(resp.body) + + if err = checkRespCode(resp.statusCode, []int{http.StatusNoContent}); err != nil { + return err + } + + return e.updateEtagAndTimestamp(resp.headers) +} + +func (e *Entity) updateMerge(force bool, verb string, options *EntityOptions) error { + query, headers := options.getParameters() + headers = mergeHeaders(headers, e.Table.tsc.client.getStandardHeaders()) + + body, err := json.Marshal(e) + if err != nil { + return err + } + headers = addBodyRelatedHeaders(headers, len(body)) + headers = addIfMatchHeader(headers, force, e.OdataEtag) + headers = addReturnContentHeaders(headers, EmptyPayload) + + uri := e.Table.tsc.client.getEndpoint(tableServiceName, e.buildPath(), query) + resp, err := e.Table.tsc.client.exec(verb, uri, headers, bytes.NewReader(body), e.Table.tsc.auth) + if err != nil { + if resp.statusCode == http.StatusPreconditionFailed { + return fmt.Errorf(etagErrorTemplate, err) + } + return err + } + defer readAndCloseBody(resp.body) + + if err = checkRespCode(resp.statusCode, []int{http.StatusNoContent}); err != nil { + return err + } + + return e.updateEtagAndTimestamp(resp.headers) +} + +func stringFromMap(props map[string]interface{}, key string) string { + value := getAndDelete(props, key) + if value != nil { + return value.(string) + } + return "" +} + +func (options *EntityOptions) getParameters() (url.Values, map[string]string) { + query := url.Values{} + headers := map[string]string{} + if options != nil { + query = addTimeout(query, options.Timeout) + headers = headersFromStruct(*options) + } + return query, headers +} 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 f679395bde27..238ac6d6d95a 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 @@ -1,123 +1,75 @@ package storage import ( - "encoding/xml" "errors" "fmt" "io" + "io/ioutil" "net/http" "net/url" "strconv" - "strings" ) -// FileServiceClient contains operations for Microsoft Azure File Service. -type FileServiceClient struct { - client Client -} - -// A Share is an entry in ShareListResponse. -type Share struct { - Name string `xml:"Name"` - Properties ShareProperties `xml:"Properties"` -} - -// A Directory is an entry in DirsAndFilesListResponse. -type Directory struct { - Name string `xml:"Name"` -} +const fourMB = uint64(4194304) +const oneTB = uint64(1099511627776) -// A File is an entry in DirsAndFilesListResponse. +// File represents a file on a share. type File struct { - Name string `xml:"Name"` - Properties FileProperties `xml:"Properties"` + fsc *FileServiceClient + Metadata map[string]string + Name string `xml:"Name"` + parent *Directory + Properties FileProperties `xml:"Properties"` + share *Share + FileCopyProperties FileCopyState } -// ShareProperties contains various properties of a share returned from -// various endpoints like ListShares. -type ShareProperties struct { - LastModified string `xml:"Last-Modified"` - Etag string `xml:"Etag"` - Quota string `xml:"Quota"` -} - -// DirectoryProperties contains various properties of a directory returned -// from various endpoints like GetDirectoryProperties. -type DirectoryProperties struct { - LastModified string `xml:"Last-Modified"` - Etag string `xml:"Etag"` -} - -// FileProperties contains various properties of a file returned from -// various endpoints like ListDirsAndFiles. +// FileProperties contains various properties of a file. type FileProperties struct { - CacheControl string `header:"x-ms-cache-control"` - ContentLength uint64 `xml:"Content-Length"` - ContentType string `header:"x-ms-content-type"` - CopyCompletionTime string - CopyID string - CopySource string - CopyProgress string - CopyStatusDesc string - CopyStatus string - Disposition string `header:"x-ms-content-disposition"` - Encoding string `header:"x-ms-content-encoding"` - Etag string - Language string `header:"x-ms-content-language"` - LastModified string - MD5 string `header:"x-ms-content-md5"` + CacheControl string `header:"x-ms-cache-control"` + Disposition string `header:"x-ms-content-disposition"` + Encoding string `header:"x-ms-content-encoding"` + Etag string + Language string `header:"x-ms-content-language"` + LastModified string + Length uint64 `xml:"Content-Length" header:"x-ms-content-length"` + MD5 string `header:"x-ms-content-md5"` + Type string `header:"x-ms-content-type"` +} + +// FileCopyState contains various properties of a file copy operation. +type FileCopyState struct { + CompletionTime string + ID string `header:"x-ms-copy-id"` + Progress string + Source string + Status string `header:"x-ms-copy-status"` + StatusDesc string } // FileStream contains file data returned from a call to GetFile. type FileStream struct { Body io.ReadCloser - Properties *FileProperties - Metadata map[string]string + ContentMD5 string } -// ShareListResponse contains the response fields from -// ListShares call. -// -// See https://msdn.microsoft.com/en-us/library/azure/dn167009.aspx -type ShareListResponse struct { - XMLName xml.Name `xml:"EnumerationResults"` - Xmlns string `xml:"xmlns,attr"` - Prefix string `xml:"Prefix"` - Marker string `xml:"Marker"` - NextMarker string `xml:"NextMarker"` - MaxResults int64 `xml:"MaxResults"` - Shares []Share `xml:"Shares>Share"` -} - -// ListSharesParameters defines the set of customizable parameters to make a -// List Shares call. -// -// See https://msdn.microsoft.com/en-us/library/azure/dn167009.aspx -type ListSharesParameters struct { - Prefix string - Marker string - Include string - MaxResults uint - Timeout uint +// FileRequestOptions will be passed to misc file operations. +// Currently just Timeout (in seconds) but could expand. +type FileRequestOptions struct { + Timeout uint // timeout duration in seconds. } -// DirsAndFilesListResponse contains the response fields from -// a List Files and Directories call. -// -// See https://msdn.microsoft.com/en-us/library/azure/dn166980.aspx -type DirsAndFilesListResponse struct { - XMLName xml.Name `xml:"EnumerationResults"` - Xmlns string `xml:"xmlns,attr"` - Marker string `xml:"Marker"` - MaxResults int64 `xml:"MaxResults"` - Directories []Directory `xml:"Entries>Directory"` - Files []File `xml:"Entries>File"` - NextMarker string `xml:"NextMarker"` +func prepareOptions(options *FileRequestOptions) url.Values { + params := url.Values{} + if options != nil { + params = addTimeout(params, options.Timeout) + } + return params } // FileRanges contains a list of file range information for a file. // -// See https://msdn.microsoft.com/en-us/library/azure/dn166984.aspx +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/List-Ranges type FileRanges struct { ContentLength uint64 LastModified string @@ -127,752 +79,384 @@ type FileRanges struct { // FileRange contains range information for a file. // -// See https://msdn.microsoft.com/en-us/library/azure/dn166984.aspx +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/List-Ranges type FileRange struct { Start uint64 `xml:"Start"` End uint64 `xml:"End"` } -// ListDirsAndFilesParameters defines the set of customizable parameters to -// make a List Files and Directories call. -// -// See https://msdn.microsoft.com/en-us/library/azure/dn166980.aspx -type ListDirsAndFilesParameters struct { - Marker string - MaxResults uint - Timeout uint -} - -// ShareHeaders contains various properties of a file and is an entry -// in SetShareProperties -type ShareHeaders struct { - Quota string `header:"x-ms-share-quota"` -} - -type compType string - -const ( - compNone compType = "" - compList compType = "list" - compMetadata compType = "metadata" - compProperties compType = "properties" - compRangeList compType = "rangelist" -) - -func (ct compType) String() string { - return string(ct) -} - -type resourceType string - -const ( - resourceDirectory resourceType = "directory" - resourceFile resourceType = "" - resourceShare resourceType = "share" -) - -func (rt resourceType) String() string { - return string(rt) -} - -func (p ListSharesParameters) getParameters() url.Values { - out := url.Values{} - - if p.Prefix != "" { - out.Set("prefix", p.Prefix) - } - if p.Marker != "" { - out.Set("marker", p.Marker) - } - if p.Include != "" { - out.Set("include", p.Include) - } - if p.MaxResults != 0 { - out.Set("maxresults", fmt.Sprintf("%v", p.MaxResults)) - } - if p.Timeout != 0 { - out.Set("timeout", fmt.Sprintf("%v", p.Timeout)) - } - - return out -} - -func (p ListDirsAndFilesParameters) getParameters() url.Values { - out := url.Values{} - - if p.Marker != "" { - out.Set("marker", p.Marker) - } - if p.MaxResults != 0 { - out.Set("maxresults", fmt.Sprintf("%v", p.MaxResults)) - } - if p.Timeout != 0 { - out.Set("timeout", fmt.Sprintf("%v", p.Timeout)) - } - - return out -} - func (fr FileRange) String() string { return fmt.Sprintf("bytes=%d-%d", fr.Start, fr.End) } -// ToPathSegment returns the URL path segment for the specified values -func ToPathSegment(parts ...string) string { - join := strings.Join(parts, "/") - if join[0] != '/' { - join = fmt.Sprintf("/%s", join) - } - return join +// builds the complete file path for this file object +func (f *File) buildPath() string { + return f.parent.buildPath() + "/" + f.Name } -// returns url.Values for the specified types -func getURLInitValues(comp compType, res resourceType) url.Values { - values := url.Values{} - if comp != compNone { - values.Set("comp", comp.String()) - } - if res != resourceFile { - values.Set("restype", res.String()) - } - return values -} - -// ListDirsAndFiles returns a list of files or directories under the specified share or -// directory. It also contains a pagination token and other response details. +// ClearRange releases the specified range of space in a file. // -// See https://msdn.microsoft.com/en-us/library/azure/dn166980.aspx -func (f FileServiceClient) ListDirsAndFiles(path string, params ListDirsAndFilesParameters) (DirsAndFilesListResponse, error) { - q := mergeParams(params.getParameters(), getURLInitValues(compList, resourceDirectory)) - - var out DirsAndFilesListResponse - resp, err := f.listContent(path, q, nil) +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Put-Range +func (f *File) ClearRange(fileRange FileRange, options *FileRequestOptions) error { + var timeout *uint + if options != nil { + timeout = &options.Timeout + } + headers, err := f.modifyRange(nil, fileRange, timeout, nil) if err != nil { - return out, err + return err } - defer resp.body.Close() - err = xmlUnmarshal(resp.body, &out) - return out, err + f.updateEtagAndLastModified(headers) + return nil } -// ListFileRanges returns the list of valid ranges for a file. +// Create creates a new file or replaces an existing one. // -// See https://msdn.microsoft.com/en-us/library/azure/dn166984.aspx -func (f FileServiceClient) ListFileRanges(path string, listRange *FileRange) (FileRanges, error) { - params := url.Values{"comp": {"rangelist"}} - - // add optional range to list - var headers map[string]string - if listRange != nil { - headers = make(map[string]string) - headers["Range"] = listRange.String() +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Create-File +func (f *File) Create(maxSize uint64, options *FileRequestOptions) error { + if maxSize > oneTB { + return fmt.Errorf("max file size is 1TB") } + params := prepareOptions(options) + headers := headersFromStruct(f.Properties) + headers["x-ms-content-length"] = strconv.FormatUint(maxSize, 10) + headers["x-ms-type"] = "file" - var out FileRanges - resp, err := f.listContent(path, params, headers) - if err != nil { - return out, err - } - - defer resp.body.Close() - var cl uint64 - cl, err = strconv.ParseUint(resp.headers.Get("x-ms-content-length"), 10, 64) + outputHeaders, err := f.fsc.createResource(f.buildPath(), resourceFile, params, mergeMDIntoExtraHeaders(f.Metadata, headers), []int{http.StatusCreated}) if err != nil { - return out, err + return err } - out.ContentLength = cl - out.ETag = resp.headers.Get("ETag") - out.LastModified = resp.headers.Get("Last-Modified") - - err = xmlUnmarshal(resp.body, &out) - return out, err + f.Properties.Length = maxSize + f.updateEtagAndLastModified(outputHeaders) + return nil } -// ListShares returns the list of shares in a storage account along with -// pagination token and other response details. +// CopyFile operation copied a file/blob from the sourceURL to the path provided. // -// See https://msdn.microsoft.com/en-us/library/azure/dd179352.aspx -func (f FileServiceClient) ListShares(params ListSharesParameters) (ShareListResponse, error) { - q := mergeParams(params.getParameters(), url.Values{"comp": {"list"}}) - - var out ShareListResponse - resp, err := f.listContent("", q, nil) - if err != nil { - return out, err - } - - defer resp.body.Close() - err = xmlUnmarshal(resp.body, &out) - return out, err -} - -// retrieves directory or share content -func (f FileServiceClient) listContent(path string, params url.Values, extraHeaders map[string]string) (*storageResponse, error) { - if err := f.checkForStorageEmulator(); err != nil { - return nil, err +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/copy-file +func (f *File) CopyFile(sourceURL string, options *FileRequestOptions) error { + extraHeaders := map[string]string{ + "x-ms-type": "file", + "x-ms-copy-source": sourceURL, } + params := prepareOptions(options) - uri := f.client.getEndpoint(fileServiceName, path, params) - headers := mergeHeaders(f.client.getStandardHeaders(), extraHeaders) - - resp, err := f.client.exec(http.MethodGet, uri, headers, nil) + headers, err := f.fsc.createResource(f.buildPath(), resourceFile, params, mergeMDIntoExtraHeaders(f.Metadata, extraHeaders), []int{http.StatusAccepted}) if err != nil { - return nil, err - } - - if err = checkRespCode(resp.statusCode, []int{http.StatusOK}); err != nil { - resp.body.Close() - return nil, err + return err } - return resp, nil + f.updateEtagLastModifiedAndCopyHeaders(headers) + return nil } -// CreateDirectory operation creates a new directory with optional metadata in the -// specified share. If a directory with the same name already exists, the operation fails. +// Delete immediately removes this file from the storage account. // -// See https://msdn.microsoft.com/en-us/library/azure/dn166993.aspx -func (f FileServiceClient) CreateDirectory(path string, metadata map[string]string) error { - return f.createResource(path, resourceDirectory, mergeMDIntoExtraHeaders(metadata, nil)) +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Delete-File2 +func (f *File) Delete(options *FileRequestOptions) error { + return f.fsc.deleteResource(f.buildPath(), resourceFile, options) } -// CreateFile operation creates a new file with optional metadata or replaces an existing one. -// Note that this only initializes the file, call PutRange to add content. +// DeleteIfExists removes this file if it exists. // -// See https://msdn.microsoft.com/en-us/library/azure/dn194271.aspx -func (f FileServiceClient) CreateFile(path string, maxSize uint64, metadata map[string]string) error { - extraHeaders := map[string]string{ - "x-ms-content-length": strconv.FormatUint(maxSize, 10), - "x-ms-type": "file", +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Delete-File2 +func (f *File) DeleteIfExists(options *FileRequestOptions) (bool, error) { + resp, err := f.fsc.deleteResourceNoClose(f.buildPath(), resourceFile, options) + if resp != nil { + defer readAndCloseBody(resp.body) + if resp.statusCode == http.StatusAccepted || resp.statusCode == http.StatusNotFound { + return resp.statusCode == http.StatusAccepted, nil + } } - return f.createResource(path, resourceFile, mergeMDIntoExtraHeaders(metadata, extraHeaders)) + return false, err } -// ClearRange releases the specified range of space in storage. -// -// See https://msdn.microsoft.com/en-us/library/azure/dn194276.aspx -func (f FileServiceClient) ClearRange(path string, fileRange FileRange) error { - return f.modifyRange(path, nil, fileRange) +// GetFileOptions includes options for a get file operation +type GetFileOptions struct { + Timeout uint + GetContentMD5 bool } -// PutRange writes a range of bytes to a file. Note that the length of bytes must -// match (rangeEnd - rangeStart) + 1 with a maximum size of 4MB. +// DownloadToStream operation downloads the file. // -// See https://msdn.microsoft.com/en-us/library/azure/dn194276.aspx -func (f FileServiceClient) PutRange(path string, bytes io.Reader, fileRange FileRange) error { - return f.modifyRange(path, bytes, fileRange) -} - -// modifies a range of bytes in the specified file -func (f FileServiceClient) modifyRange(path string, bytes io.Reader, fileRange FileRange) error { - if err := f.checkForStorageEmulator(); err != nil { - return err - } - if fileRange.End < fileRange.Start { - return errors.New("the value for rangeEnd must be greater than or equal to rangeStart") - } - if bytes != nil && fileRange.End-fileRange.Start > 4194304 { - return errors.New("range cannot exceed 4MB in size") - } - - uri := f.client.getEndpoint(fileServiceName, path, url.Values{"comp": {"range"}}) - - // default to clear - write := "clear" - cl := uint64(0) - - // if bytes is not nil then this is an update operation - if bytes != nil { - write = "update" - cl = (fileRange.End - fileRange.Start) + 1 - } - - extraHeaders := map[string]string{ - "Content-Length": strconv.FormatUint(cl, 10), - "Range": fileRange.String(), - "x-ms-write": write, - } - - headers := mergeHeaders(f.client.getStandardHeaders(), extraHeaders) - resp, err := f.client.exec(http.MethodPut, uri, headers, bytes) +// See: https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/get-file +func (f *File) DownloadToStream(options *FileRequestOptions) (io.ReadCloser, error) { + params := prepareOptions(options) + resp, err := f.fsc.getResourceNoClose(f.buildPath(), compNone, resourceFile, params, http.MethodGet, nil) if err != nil { - return err + return nil, err } - defer resp.body.Close() - return checkRespCode(resp.statusCode, []int{http.StatusCreated}) + if err = checkRespCode(resp.statusCode, []int{http.StatusOK}); err != nil { + readAndCloseBody(resp.body) + return nil, err + } + return resp.body, nil } -// GetFile operation reads or downloads a file from the system, including its -// metadata and properties. +// DownloadRangeToStream operation downloads the specified range of this file with optional MD5 hash. // // See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/get-file -func (f FileServiceClient) GetFile(path string, fileRange *FileRange) (*FileStream, error) { - var extraHeaders map[string]string - if fileRange != nil { - extraHeaders = map[string]string{ - "Range": fileRange.String(), +func (f *File) DownloadRangeToStream(fileRange FileRange, options *GetFileOptions) (fs FileStream, err error) { + extraHeaders := map[string]string{ + "Range": fileRange.String(), + } + params := url.Values{} + if options != nil { + if options.GetContentMD5 { + if isRangeTooBig(fileRange) { + return fs, fmt.Errorf("must specify a range less than or equal to 4MB when getContentMD5 is true") + } + extraHeaders["x-ms-range-get-content-md5"] = "true" } + params = addTimeout(params, options.Timeout) } - resp, err := f.getResourceNoClose(path, compNone, resourceFile, http.MethodGet, extraHeaders) + resp, err := f.fsc.getResourceNoClose(f.buildPath(), compNone, resourceFile, params, http.MethodGet, extraHeaders) if err != nil { - return nil, err + return fs, err } if err = checkRespCode(resp.statusCode, []int{http.StatusOK, http.StatusPartialContent}); err != nil { - resp.body.Close() - return nil, err - } - - props, err := getFileProps(resp.headers) - md := getFileMDFromHeaders(resp.headers) - return &FileStream{Body: resp.body, Properties: props, Metadata: md}, nil -} - -// CreateShare operation creates a new share with optional metadata under the specified account. -// If the share with the same name already exists, the operation fails. -// -// See https://msdn.microsoft.com/en-us/library/azure/dn167008.aspx -func (f FileServiceClient) CreateShare(name string, metadata map[string]string) error { - return f.createResource(ToPathSegment(name), resourceShare, mergeMDIntoExtraHeaders(metadata, nil)) -} - -// DirectoryExists returns true if the specified directory exists on the specified share. -func (f FileServiceClient) DirectoryExists(path string) (bool, error) { - return f.resourceExists(path, resourceDirectory) -} - -// FileExists returns true if the specified file exists. -func (f FileServiceClient) FileExists(path string) (bool, error) { - return f.resourceExists(path, resourceFile) -} - -// ShareExists returns true if a share with given name exists -// on the storage account, otherwise returns false. -func (f FileServiceClient) ShareExists(name string) (bool, error) { - return f.resourceExists(ToPathSegment(name), resourceShare) -} - -// returns true if the specified directory or share exists -func (f FileServiceClient) resourceExists(path string, res resourceType) (bool, error) { - if err := f.checkForStorageEmulator(); err != nil { - return false, err + readAndCloseBody(resp.body) + return fs, err } - uri := f.client.getEndpoint(fileServiceName, path, getURLInitValues(compNone, res)) - headers := f.client.getStandardHeaders() - - resp, err := f.client.exec(http.MethodHead, uri, headers, nil) - if resp != nil { - defer resp.body.Close() - if resp.statusCode == http.StatusOK || resp.statusCode == http.StatusNotFound { - return resp.statusCode == http.StatusOK, nil - } + fs.Body = resp.body + if options != nil && options.GetContentMD5 { + fs.ContentMD5 = resp.headers.Get("Content-MD5") } - return false, err -} - -// GetDirectoryURL gets the canonical URL to the directory with the specified name -// in the specified share. This method does not create a publicly accessible URL if -// the file is private and this method does not check if the directory exists. -func (f FileServiceClient) GetDirectoryURL(path string) string { - return f.client.getEndpoint(fileServiceName, path, url.Values{}) -} - -// GetShareURL gets the canonical URL to the share with the specified name in the -// specified container. This method does not create a publicly accessible URL if -// the file is private and this method does not check if the share exists. -func (f FileServiceClient) GetShareURL(name string) string { - return f.client.getEndpoint(fileServiceName, ToPathSegment(name), url.Values{}) + return fs, nil } -// CreateDirectoryIfNotExists creates a new directory on the specified share -// if it does not exist. Returns true if directory is newly created or false -// if the directory already exists. -// -// See https://msdn.microsoft.com/en-us/library/azure/dn166993.aspx -func (f FileServiceClient) CreateDirectoryIfNotExists(path string) (bool, error) { - resp, err := f.createResourceNoClose(path, resourceDirectory, nil) - if resp != nil { - defer resp.body.Close() - if resp.statusCode == http.StatusCreated || resp.statusCode == http.StatusConflict { - return resp.statusCode == http.StatusCreated, nil - } +// Exists returns true if this file exists. +func (f *File) Exists() (bool, error) { + exists, headers, err := f.fsc.resourceExists(f.buildPath(), resourceFile) + if exists { + f.updateEtagAndLastModified(headers) + f.updateProperties(headers) } - return false, err + return exists, err } -// CreateShareIfNotExists creates a new share under the specified account if -// it does not exist. Returns true if container is newly created or false if -// container already exists. -// -// See https://msdn.microsoft.com/en-us/library/azure/dn167008.aspx -func (f FileServiceClient) CreateShareIfNotExists(name string) (bool, error) { - resp, err := f.createResourceNoClose(ToPathSegment(name), resourceShare, nil) - if resp != nil { - defer resp.body.Close() - if resp.statusCode == http.StatusCreated || resp.statusCode == http.StatusConflict { - return resp.statusCode == http.StatusCreated, nil - } - } - return false, err -} - -// creates a resource depending on the specified resource type -func (f FileServiceClient) createResource(path string, res resourceType, extraHeaders map[string]string) error { - resp, err := f.createResourceNoClose(path, res, extraHeaders) +// FetchAttributes updates metadata and properties for this file. +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/get-file-properties +func (f *File) FetchAttributes(options *FileRequestOptions) error { + params := prepareOptions(options) + headers, err := f.fsc.getResourceHeaders(f.buildPath(), compNone, resourceFile, params, http.MethodHead) if err != nil { return err } - defer resp.body.Close() - return checkRespCode(resp.statusCode, []int{http.StatusCreated}) + + f.updateEtagAndLastModified(headers) + f.updateProperties(headers) + f.Metadata = getMetadataFromHeaders(headers) + return nil } -// creates a resource depending on the specified resource type, doesn't close the response body -func (f FileServiceClient) createResourceNoClose(path string, res resourceType, extraHeaders map[string]string) (*storageResponse, error) { - if err := f.checkForStorageEmulator(); err != nil { - return nil, err +// returns true if the range is larger than 4MB +func isRangeTooBig(fileRange FileRange) bool { + if fileRange.End-fileRange.Start > fourMB { + return true } - values := getURLInitValues(compNone, res) - uri := f.client.getEndpoint(fileServiceName, path, values) - headers := mergeHeaders(f.client.getStandardHeaders(), extraHeaders) - - return f.client.exec(http.MethodPut, uri, headers, nil) + return false } -// GetDirectoryProperties provides various information about the specified directory. -// -// See https://msdn.microsoft.com/en-us/library/azure/dn194272.aspx -func (f FileServiceClient) GetDirectoryProperties(path string) (*DirectoryProperties, error) { - headers, err := f.getResourceHeaders(path, compNone, resourceDirectory, http.MethodHead) - if err != nil { - return nil, err - } - - return &DirectoryProperties{ - LastModified: headers.Get("Last-Modified"), - Etag: headers.Get("Etag"), - }, nil +// ListRangesOptions includes options for a list file ranges operation +type ListRangesOptions struct { + Timeout uint + ListRange *FileRange } -// GetFileProperties provides various information about the specified file. +// ListRanges returns the list of valid ranges for this file. // -// See https://msdn.microsoft.com/en-us/library/azure/dn166971.aspx -func (f FileServiceClient) GetFileProperties(path string) (*FileProperties, error) { - headers, err := f.getResourceHeaders(path, compNone, resourceFile, http.MethodHead) - if err != nil { - return nil, err - } - return getFileProps(headers) -} +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/List-Ranges +func (f *File) ListRanges(options *ListRangesOptions) (*FileRanges, error) { + params := url.Values{"comp": {"rangelist"}} -// returns file properties from the specified HTTP header -func getFileProps(header http.Header) (*FileProperties, error) { - size, err := strconv.ParseUint(header.Get("Content-Length"), 10, 64) - if err != nil { - return nil, err + // add optional range to list + var headers map[string]string + if options != nil { + params = addTimeout(params, options.Timeout) + if options.ListRange != nil { + headers = make(map[string]string) + headers["Range"] = options.ListRange.String() + } } - return &FileProperties{ - CacheControl: header.Get("Cache-Control"), - ContentLength: size, - ContentType: header.Get("Content-Type"), - CopyCompletionTime: header.Get("x-ms-copy-completion-time"), - CopyID: header.Get("x-ms-copy-id"), - CopyProgress: header.Get("x-ms-copy-progress"), - CopySource: header.Get("x-ms-copy-source"), - CopyStatus: header.Get("x-ms-copy-status"), - CopyStatusDesc: header.Get("x-ms-copy-status-description"), - Disposition: header.Get("Content-Disposition"), - Encoding: header.Get("Content-Encoding"), - Etag: header.Get("ETag"), - Language: header.Get("Content-Language"), - LastModified: header.Get("Last-Modified"), - MD5: header.Get("Content-MD5"), - }, nil -} - -// GetShareProperties provides various information about the specified -// file. See https://msdn.microsoft.com/en-us/library/azure/dn689099.aspx -func (f FileServiceClient) GetShareProperties(name string) (*ShareProperties, error) { - headers, err := f.getResourceHeaders(ToPathSegment(name), compNone, resourceShare, http.MethodHead) + resp, err := f.fsc.listContent(f.buildPath(), params, headers) if err != nil { return nil, err } - return &ShareProperties{ - LastModified: headers.Get("Last-Modified"), - Etag: headers.Get("Etag"), - Quota: headers.Get("x-ms-share-quota"), - }, nil -} -// returns HTTP header data for the specified directory or share -func (f FileServiceClient) getResourceHeaders(path string, comp compType, res resourceType, verb string) (http.Header, error) { - resp, err := f.getResourceNoClose(path, comp, res, verb, nil) + defer resp.body.Close() + var cl uint64 + cl, err = strconv.ParseUint(resp.headers.Get("x-ms-content-length"), 10, 64) if err != nil { + ioutil.ReadAll(resp.body) return nil, err } - defer resp.body.Close() - if err = checkRespCode(resp.statusCode, []int{http.StatusOK}); err != nil { - return nil, err - } + var out FileRanges + out.ContentLength = cl + out.ETag = resp.headers.Get("ETag") + out.LastModified = resp.headers.Get("Last-Modified") - return resp.headers, nil + err = xmlUnmarshal(resp.body, &out) + return &out, err } -// gets the specified resource, doesn't close the response body -func (f FileServiceClient) getResourceNoClose(path string, comp compType, res resourceType, verb string, extraHeaders map[string]string) (*storageResponse, error) { - if err := f.checkForStorageEmulator(); err != nil { +// modifies a range of bytes in this file +func (f *File) modifyRange(bytes io.Reader, fileRange FileRange, timeout *uint, contentMD5 *string) (http.Header, error) { + if err := f.fsc.checkForStorageEmulator(); err != nil { return nil, err } + if fileRange.End < fileRange.Start { + return nil, errors.New("the value for rangeEnd must be greater than or equal to rangeStart") + } + if bytes != nil && isRangeTooBig(fileRange) { + return nil, errors.New("range cannot exceed 4MB in size") + } - params := getURLInitValues(comp, res) - uri := f.client.getEndpoint(fileServiceName, path, params) - headers := mergeHeaders(f.client.getStandardHeaders(), extraHeaders) - - return f.client.exec(verb, uri, headers, nil) -} - -// SetFileProperties operation sets system properties on the specified file. -// -// Some keys may be converted to Camel-Case before sending. All keys -// are returned in lower case by SetFileProperties. HTTP header names -// are case-insensitive so case munging should not matter to other -// applications either. -// -// See https://msdn.microsoft.com/en-us/library/azure/dn166975.aspx -func (f FileServiceClient) SetFileProperties(path string, props FileProperties) error { - return f.setResourceHeaders(path, compProperties, resourceFile, headersFromStruct(props)) -} - -// SetShareProperties replaces the ShareHeaders for the specified file. -// -// Some keys may be converted to Camel-Case before sending. All keys -// are returned in lower case by SetShareProperties. HTTP header names -// are case-insensitive so case munging should not matter to other -// applications either. -// -// See https://msdn.microsoft.com/en-us/library/azure/mt427368.aspx -func (f FileServiceClient) SetShareProperties(name string, shareHeaders ShareHeaders) error { - return f.setResourceHeaders(ToPathSegment(name), compProperties, resourceShare, headersFromStruct(shareHeaders)) -} + params := url.Values{"comp": {"range"}} + if timeout != nil { + params = addTimeout(params, *timeout) + } -// DeleteDirectory operation removes the specified empty directory. -// -// See https://msdn.microsoft.com/en-us/library/azure/dn166969.aspx -func (f FileServiceClient) DeleteDirectory(path string) error { - return f.deleteResource(path, resourceDirectory) -} + uri := f.fsc.client.getEndpoint(fileServiceName, f.buildPath(), params) -// DeleteFile operation immediately removes the file from the storage account. -// -// See https://msdn.microsoft.com/en-us/library/azure/dn689085.aspx -func (f FileServiceClient) DeleteFile(path string) error { - return f.deleteResource(path, resourceFile) -} + // default to clear + write := "clear" + cl := uint64(0) -// DeleteShare operation marks the specified share for deletion. The share -// and any files contained within it are later deleted during garbage -// collection. -// -// See https://msdn.microsoft.com/en-us/library/azure/dn689090.aspx -func (f FileServiceClient) DeleteShare(name string) error { - return f.deleteResource(ToPathSegment(name), resourceShare) -} + // if bytes is not nil then this is an update operation + if bytes != nil { + write = "update" + cl = (fileRange.End - fileRange.Start) + 1 + } -// DeleteShareIfExists operation marks the specified share for deletion if it -// exists. The share and any files contained within it are later deleted during -// garbage collection. Returns true if share existed and deleted with this call, -// false otherwise. -// -// See https://msdn.microsoft.com/en-us/library/azure/dn689090.aspx -func (f FileServiceClient) DeleteShareIfExists(name string) (bool, error) { - resp, err := f.deleteResourceNoClose(ToPathSegment(name), resourceShare) - if resp != nil { - defer resp.body.Close() - if resp.statusCode == http.StatusAccepted || resp.statusCode == http.StatusNotFound { - return resp.statusCode == http.StatusAccepted, nil - } + extraHeaders := map[string]string{ + "Content-Length": strconv.FormatUint(cl, 10), + "Range": fileRange.String(), + "x-ms-write": write, } - return false, err -} -// deletes the resource and returns the response -func (f FileServiceClient) deleteResource(path string, res resourceType) error { - resp, err := f.deleteResourceNoClose(path, res) - if err != nil { - return err + if contentMD5 != nil { + extraHeaders["Content-MD5"] = *contentMD5 } - defer resp.body.Close() - return checkRespCode(resp.statusCode, []int{http.StatusAccepted}) -} -// deletes the resource and returns the response, doesn't close the response body -func (f FileServiceClient) deleteResourceNoClose(path string, res resourceType) (*storageResponse, error) { - if err := f.checkForStorageEmulator(); err != nil { + headers := mergeHeaders(f.fsc.client.getStandardHeaders(), extraHeaders) + resp, err := f.fsc.client.exec(http.MethodPut, uri, headers, bytes, f.fsc.auth) + if err != nil { return nil, err } - - values := getURLInitValues(compNone, res) - uri := f.client.getEndpoint(fileServiceName, path, values) - return f.client.exec(http.MethodDelete, uri, f.client.getStandardHeaders(), nil) -} - -// SetDirectoryMetadata replaces the metadata for the specified directory. -// -// Some keys may be converted to Camel-Case before sending. All keys -// are returned in lower case by GetDirectoryMetadata. HTTP header names -// are case-insensitive so case munging should not matter to other -// applications either. -// -// See https://msdn.microsoft.com/en-us/library/azure/mt427370.aspx -func (f FileServiceClient) SetDirectoryMetadata(path string, metadata map[string]string) error { - return f.setResourceHeaders(path, compMetadata, resourceDirectory, mergeMDIntoExtraHeaders(metadata, nil)) + defer readAndCloseBody(resp.body) + return resp.headers, checkRespCode(resp.statusCode, []int{http.StatusCreated}) } -// SetFileMetadata replaces the metadata for the specified file. +// SetMetadata replaces the metadata for this file. // // Some keys may be converted to Camel-Case before sending. All keys // are returned in lower case by GetFileMetadata. HTTP header names // are case-insensitive so case munging should not matter to other // applications either. // -// See https://msdn.microsoft.com/en-us/library/azure/dn689097.aspx -func (f FileServiceClient) SetFileMetadata(path string, metadata map[string]string) error { - return f.setResourceHeaders(path, compMetadata, resourceFile, mergeMDIntoExtraHeaders(metadata, nil)) +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Set-File-Metadata +func (f *File) SetMetadata(options *FileRequestOptions) error { + headers, err := f.fsc.setResourceHeaders(f.buildPath(), compMetadata, resourceFile, mergeMDIntoExtraHeaders(f.Metadata, nil), options) + if err != nil { + return err + } + + f.updateEtagAndLastModified(headers) + return nil } -// SetShareMetadata replaces the metadata for the specified Share. +// SetProperties sets system properties on this file. // // Some keys may be converted to Camel-Case before sending. All keys -// are returned in lower case by GetShareMetadata. HTTP header names +// are returned in lower case by SetFileProperties. HTTP header names // are case-insensitive so case munging should not matter to other // applications either. // -// See https://msdn.microsoft.com/en-us/library/azure/dd179414.aspx -func (f FileServiceClient) SetShareMetadata(name string, metadata map[string]string) error { - return f.setResourceHeaders(ToPathSegment(name), compMetadata, resourceShare, mergeMDIntoExtraHeaders(metadata, nil)) +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Set-File-Properties +func (f *File) SetProperties(options *FileRequestOptions) error { + headers, err := f.fsc.setResourceHeaders(f.buildPath(), compProperties, resourceFile, headersFromStruct(f.Properties), options) + if err != nil { + return err + } + + f.updateEtagAndLastModified(headers) + return nil } -// merges metadata into extraHeaders and returns extraHeaders -func mergeMDIntoExtraHeaders(metadata, extraHeaders map[string]string) map[string]string { - if metadata == nil && extraHeaders == nil { - return nil - } - if extraHeaders == nil { - extraHeaders = make(map[string]string) - } - for k, v := range metadata { - extraHeaders[userDefinedMetadataHeaderPrefix+k] = v - } - return extraHeaders +// updates Etag and last modified date +func (f *File) updateEtagAndLastModified(headers http.Header) { + f.Properties.Etag = headers.Get("Etag") + f.Properties.LastModified = headers.Get("Last-Modified") } -// merges extraHeaders into headers and returns headers -func mergeHeaders(headers, extraHeaders map[string]string) map[string]string { - for k, v := range extraHeaders { - headers[k] = v - } - return headers +// updates Etag, last modified date and x-ms-copy-id +func (f *File) updateEtagLastModifiedAndCopyHeaders(headers http.Header) { + f.Properties.Etag = headers.Get("Etag") + f.Properties.LastModified = headers.Get("Last-Modified") + f.FileCopyProperties.ID = headers.Get("X-Ms-Copy-Id") + f.FileCopyProperties.Status = headers.Get("X-Ms-Copy-Status") } -// sets extra header data for the specified resource -func (f FileServiceClient) setResourceHeaders(path string, comp compType, res resourceType, extraHeaders map[string]string) error { - if err := f.checkForStorageEmulator(); err != nil { - return err +// updates file properties from the specified HTTP header +func (f *File) updateProperties(header http.Header) { + size, err := strconv.ParseUint(header.Get("Content-Length"), 10, 64) + if err == nil { + f.Properties.Length = size } - params := getURLInitValues(comp, res) - uri := f.client.getEndpoint(fileServiceName, path, params) - headers := mergeHeaders(f.client.getStandardHeaders(), extraHeaders) - - resp, err := f.client.exec(http.MethodPut, uri, headers, nil) - if err != nil { - return err - } - defer resp.body.Close() - - return checkRespCode(resp.statusCode, []int{http.StatusOK}) + f.updateEtagAndLastModified(header) + f.Properties.CacheControl = header.Get("Cache-Control") + f.Properties.Disposition = header.Get("Content-Disposition") + f.Properties.Encoding = header.Get("Content-Encoding") + f.Properties.Language = header.Get("Content-Language") + f.Properties.MD5 = header.Get("Content-MD5") + f.Properties.Type = header.Get("Content-Type") } -// GetDirectoryMetadata returns all user-defined metadata for the specified directory. -// -// All metadata keys will be returned in lower case. (HTTP header -// names are case-insensitive.) -// -// See https://msdn.microsoft.com/en-us/library/azure/mt427371.aspx -func (f FileServiceClient) GetDirectoryMetadata(path string) (map[string]string, error) { - return f.getMetadata(path, resourceDirectory) +// URL gets the canonical URL to this file. +// This method does not create a publicly accessible URL if the file +// is private and this method does not check if the file exists. +func (f *File) URL() string { + return f.fsc.client.getEndpoint(fileServiceName, f.buildPath(), nil) } -// GetFileMetadata returns all user-defined metadata for the specified file. -// -// All metadata keys will be returned in lower case. (HTTP header -// names are case-insensitive.) -// -// See https://msdn.microsoft.com/en-us/library/azure/dn689098.aspx -func (f FileServiceClient) GetFileMetadata(path string) (map[string]string, error) { - return f.getMetadata(path, resourceFile) +// WriteRangeOptions includes opptions for a write file range operation +type WriteRangeOptions struct { + Timeout uint + ContentMD5 string } -// GetShareMetadata returns all user-defined metadata for the specified share. -// -// All metadata keys will be returned in lower case. (HTTP header -// names are case-insensitive.) +// WriteRange writes a range of bytes to this file with an optional MD5 hash of the content (inside +// options parameter). Note that the length of bytes must match (rangeEnd - rangeStart) + 1 with +// a maximum size of 4MB. // -// See https://msdn.microsoft.com/en-us/library/azure/dd179414.aspx -func (f FileServiceClient) GetShareMetadata(name string) (map[string]string, error) { - return f.getMetadata(ToPathSegment(name), resourceShare) -} - -// gets metadata for the specified resource -func (f FileServiceClient) getMetadata(path string, res resourceType) (map[string]string, error) { - if err := f.checkForStorageEmulator(); err != nil { - return nil, err +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Put-Range +func (f *File) WriteRange(bytes io.Reader, fileRange FileRange, options *WriteRangeOptions) error { + if bytes == nil { + return errors.New("bytes cannot be nil") } - - headers, err := f.getResourceHeaders(path, compMetadata, res, http.MethodGet) - if err != nil { - return nil, err + var timeout *uint + var md5 *string + if options != nil { + timeout = &options.Timeout + md5 = &options.ContentMD5 } - return getFileMDFromHeaders(headers), nil -} - -// returns a map of custom metadata values from the specified HTTP header -func getFileMDFromHeaders(header http.Header) map[string]string { - metadata := make(map[string]string) - for k, v := range header { - // Can't trust CanonicalHeaderKey() to munge case - // reliably. "_" is allowed in identifiers: - // https://msdn.microsoft.com/en-us/library/azure/dd179414.aspx - // https://msdn.microsoft.com/library/aa664670(VS.71).aspx - // http://tools.ietf.org/html/rfc7230#section-3.2 - // ...but "_" is considered invalid by - // CanonicalMIMEHeaderKey in - // https://golang.org/src/net/textproto/reader.go?s=14615:14659#L542 - // so k can be "X-Ms-Meta-Foo" or "x-ms-meta-foo_bar". - k = strings.ToLower(k) - if len(v) == 0 || !strings.HasPrefix(k, strings.ToLower(userDefinedMetadataHeaderPrefix)) { - continue - } - // metadata["foo"] = content of the last X-Ms-Meta-Foo header - k = k[len(userDefinedMetadataHeaderPrefix):] - metadata[k] = v[len(v)-1] + headers, err := f.modifyRange(bytes, fileRange, timeout, md5) + if err != nil { + return err } - return metadata -} -//checkForStorageEmulator determines if the client is setup for use with -//Azure Storage Emulator, and returns a relevant error -func (f FileServiceClient) checkForStorageEmulator() error { - if f.client.accountName == StorageEmulatorAccountName { - return fmt.Errorf("Error: File service is not currently supported by Azure Storage Emulator") - } + f.updateEtagAndLastModified(headers) return nil } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/fileserviceclient.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/fileserviceclient.go new file mode 100644 index 000000000000..81217bdfa80b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/fileserviceclient.go @@ -0,0 +1,324 @@ +package storage + +import ( + "encoding/xml" + "fmt" + "net/http" + "net/url" + "strconv" +) + +// FileServiceClient contains operations for Microsoft Azure File Service. +type FileServiceClient struct { + client Client + auth authentication +} + +// ListSharesParameters defines the set of customizable parameters to make a +// List Shares call. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/List-Shares +type ListSharesParameters struct { + Prefix string + Marker string + Include string + MaxResults uint + Timeout uint +} + +// ShareListResponse contains the response fields from +// ListShares call. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/List-Shares +type ShareListResponse struct { + XMLName xml.Name `xml:"EnumerationResults"` + Xmlns string `xml:"xmlns,attr"` + Prefix string `xml:"Prefix"` + Marker string `xml:"Marker"` + NextMarker string `xml:"NextMarker"` + MaxResults int64 `xml:"MaxResults"` + Shares []Share `xml:"Shares>Share"` +} + +type compType string + +const ( + compNone compType = "" + compList compType = "list" + compMetadata compType = "metadata" + compProperties compType = "properties" + compRangeList compType = "rangelist" +) + +func (ct compType) String() string { + return string(ct) +} + +type resourceType string + +const ( + resourceDirectory resourceType = "directory" + resourceFile resourceType = "" + resourceShare resourceType = "share" +) + +func (rt resourceType) String() string { + return string(rt) +} + +func (p ListSharesParameters) getParameters() url.Values { + out := url.Values{} + + if p.Prefix != "" { + out.Set("prefix", p.Prefix) + } + if p.Marker != "" { + out.Set("marker", p.Marker) + } + if p.Include != "" { + out.Set("include", p.Include) + } + if p.MaxResults != 0 { + out.Set("maxresults", strconv.FormatUint(uint64(p.MaxResults), 10)) + } + if p.Timeout != 0 { + out.Set("timeout", strconv.FormatUint(uint64(p.Timeout), 10)) + } + + return out +} + +func (p ListDirsAndFilesParameters) getParameters() url.Values { + out := url.Values{} + + if p.Prefix != "" { + out.Set("prefix", p.Prefix) + } + if p.Marker != "" { + out.Set("marker", p.Marker) + } + if p.MaxResults != 0 { + out.Set("maxresults", strconv.FormatUint(uint64(p.MaxResults), 10)) + } + out = addTimeout(out, p.Timeout) + + return out +} + +// returns url.Values for the specified types +func getURLInitValues(comp compType, res resourceType) url.Values { + values := url.Values{} + if comp != compNone { + values.Set("comp", comp.String()) + } + if res != resourceFile { + values.Set("restype", res.String()) + } + return values +} + +// GetShareReference returns a Share object for the specified share name. +func (f *FileServiceClient) GetShareReference(name string) *Share { + return &Share{ + fsc: f, + Name: name, + Properties: ShareProperties{ + Quota: -1, + }, + } +} + +// ListShares returns the list of shares in a storage account along with +// pagination token and other response details. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/list-shares +func (f FileServiceClient) ListShares(params ListSharesParameters) (*ShareListResponse, error) { + q := mergeParams(params.getParameters(), url.Values{"comp": {"list"}}) + + var out ShareListResponse + resp, err := f.listContent("", q, nil) + if err != nil { + return nil, err + } + defer resp.body.Close() + err = xmlUnmarshal(resp.body, &out) + + // assign our client to the newly created Share objects + for i := range out.Shares { + out.Shares[i].fsc = &f + } + return &out, err +} + +// GetServiceProperties gets the properties of your storage account's file service. +// File service does not support logging +// See: https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/get-file-service-properties +func (f *FileServiceClient) GetServiceProperties() (*ServiceProperties, error) { + return f.client.getServiceProperties(fileServiceName, f.auth) +} + +// SetServiceProperties sets the properties of your storage account's file service. +// File service does not support logging +// See: https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/set-file-service-properties +func (f *FileServiceClient) SetServiceProperties(props ServiceProperties) error { + return f.client.setServiceProperties(props, fileServiceName, f.auth) +} + +// retrieves directory or share content +func (f FileServiceClient) listContent(path string, params url.Values, extraHeaders map[string]string) (*storageResponse, error) { + if err := f.checkForStorageEmulator(); err != nil { + return nil, err + } + + uri := f.client.getEndpoint(fileServiceName, path, params) + extraHeaders = f.client.protectUserAgent(extraHeaders) + headers := mergeHeaders(f.client.getStandardHeaders(), extraHeaders) + + resp, err := f.client.exec(http.MethodGet, uri, headers, nil, f.auth) + if err != nil { + return nil, err + } + + if err = checkRespCode(resp.statusCode, []int{http.StatusOK}); err != nil { + readAndCloseBody(resp.body) + return nil, err + } + + return resp, nil +} + +// returns true if the specified resource exists +func (f FileServiceClient) resourceExists(path string, res resourceType) (bool, http.Header, error) { + if err := f.checkForStorageEmulator(); err != nil { + return false, nil, err + } + + uri := f.client.getEndpoint(fileServiceName, path, getURLInitValues(compNone, res)) + headers := f.client.getStandardHeaders() + + resp, err := f.client.exec(http.MethodHead, uri, headers, nil, f.auth) + if resp != nil { + defer readAndCloseBody(resp.body) + if resp.statusCode == http.StatusOK || resp.statusCode == http.StatusNotFound { + return resp.statusCode == http.StatusOK, resp.headers, nil + } + } + return false, nil, err +} + +// creates a resource depending on the specified resource type +func (f FileServiceClient) createResource(path string, res resourceType, urlParams url.Values, extraHeaders map[string]string, expectedResponseCodes []int) (http.Header, error) { + resp, err := f.createResourceNoClose(path, res, urlParams, extraHeaders) + if err != nil { + return nil, err + } + defer readAndCloseBody(resp.body) + return resp.headers, checkRespCode(resp.statusCode, expectedResponseCodes) +} + +// creates a resource depending on the specified resource type, doesn't close the response body +func (f FileServiceClient) createResourceNoClose(path string, res resourceType, urlParams url.Values, extraHeaders map[string]string) (*storageResponse, error) { + if err := f.checkForStorageEmulator(); err != nil { + return nil, err + } + + values := getURLInitValues(compNone, res) + combinedParams := mergeParams(values, urlParams) + uri := f.client.getEndpoint(fileServiceName, path, combinedParams) + extraHeaders = f.client.protectUserAgent(extraHeaders) + headers := mergeHeaders(f.client.getStandardHeaders(), extraHeaders) + + return f.client.exec(http.MethodPut, uri, headers, nil, f.auth) +} + +// returns HTTP header data for the specified directory or share +func (f FileServiceClient) getResourceHeaders(path string, comp compType, res resourceType, params url.Values, verb string) (http.Header, error) { + resp, err := f.getResourceNoClose(path, comp, res, params, verb, nil) + if err != nil { + return nil, err + } + defer readAndCloseBody(resp.body) + + if err = checkRespCode(resp.statusCode, []int{http.StatusOK}); err != nil { + return nil, err + } + + return resp.headers, nil +} + +// gets the specified resource, doesn't close the response body +func (f FileServiceClient) getResourceNoClose(path string, comp compType, res resourceType, params url.Values, verb string, extraHeaders map[string]string) (*storageResponse, error) { + if err := f.checkForStorageEmulator(); err != nil { + return nil, err + } + + params = mergeParams(params, getURLInitValues(comp, res)) + uri := f.client.getEndpoint(fileServiceName, path, params) + headers := mergeHeaders(f.client.getStandardHeaders(), extraHeaders) + + return f.client.exec(verb, uri, headers, nil, f.auth) +} + +// deletes the resource and returns the response +func (f FileServiceClient) deleteResource(path string, res resourceType, options *FileRequestOptions) error { + resp, err := f.deleteResourceNoClose(path, res, options) + if err != nil { + return err + } + defer readAndCloseBody(resp.body) + return checkRespCode(resp.statusCode, []int{http.StatusAccepted}) +} + +// deletes the resource and returns the response, doesn't close the response body +func (f FileServiceClient) deleteResourceNoClose(path string, res resourceType, options *FileRequestOptions) (*storageResponse, error) { + if err := f.checkForStorageEmulator(); err != nil { + return nil, err + } + + values := mergeParams(getURLInitValues(compNone, res), prepareOptions(options)) + uri := f.client.getEndpoint(fileServiceName, path, values) + return f.client.exec(http.MethodDelete, uri, f.client.getStandardHeaders(), nil, f.auth) +} + +// merges metadata into extraHeaders and returns extraHeaders +func mergeMDIntoExtraHeaders(metadata, extraHeaders map[string]string) map[string]string { + if metadata == nil && extraHeaders == nil { + return nil + } + if extraHeaders == nil { + extraHeaders = make(map[string]string) + } + for k, v := range metadata { + extraHeaders[userDefinedMetadataHeaderPrefix+k] = v + } + return extraHeaders +} + +// sets extra header data for the specified resource +func (f FileServiceClient) setResourceHeaders(path string, comp compType, res resourceType, extraHeaders map[string]string, options *FileRequestOptions) (http.Header, error) { + if err := f.checkForStorageEmulator(); err != nil { + return nil, err + } + + params := mergeParams(getURLInitValues(comp, res), prepareOptions(options)) + uri := f.client.getEndpoint(fileServiceName, path, params) + extraHeaders = f.client.protectUserAgent(extraHeaders) + headers := mergeHeaders(f.client.getStandardHeaders(), extraHeaders) + + resp, err := f.client.exec(http.MethodPut, uri, headers, nil, f.auth) + if err != nil { + return nil, err + } + defer readAndCloseBody(resp.body) + + return resp.headers, checkRespCode(resp.statusCode, []int{http.StatusOK}) +} + +//checkForStorageEmulator determines if the client is setup for use with +//Azure Storage Emulator, and returns a relevant error +func (f FileServiceClient) checkForStorageEmulator() error { + if f.client.accountName == StorageEmulatorAccountName { + return fmt.Errorf("Error: File service is not currently supported by Azure Storage Emulator") + } + return nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/leaseblob.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/leaseblob.go new file mode 100644 index 000000000000..415b740183b3 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/leaseblob.go @@ -0,0 +1,187 @@ +package storage + +import ( + "errors" + "net/http" + "net/url" + "strconv" + "time" +) + +// lease constants. +const ( + leaseHeaderPrefix = "x-ms-lease-" + headerLeaseID = "x-ms-lease-id" + leaseAction = "x-ms-lease-action" + leaseBreakPeriod = "x-ms-lease-break-period" + leaseDuration = "x-ms-lease-duration" + leaseProposedID = "x-ms-proposed-lease-id" + leaseTime = "x-ms-lease-time" + + acquireLease = "acquire" + renewLease = "renew" + changeLease = "change" + releaseLease = "release" + breakLease = "break" +) + +// leasePut is common PUT code for the various acquire/release/break etc functions. +func (b *Blob) leaseCommonPut(headers map[string]string, expectedStatus int, options *LeaseOptions) (http.Header, error) { + params := url.Values{"comp": {"lease"}} + + if options != nil { + params = addTimeout(params, options.Timeout) + headers = mergeHeaders(headers, headersFromStruct(*options)) + } + uri := b.Container.bsc.client.getEndpoint(blobServiceName, b.buildPath(), params) + + resp, err := b.Container.bsc.client.exec(http.MethodPut, uri, headers, nil, b.Container.bsc.auth) + if err != nil { + return nil, err + } + defer readAndCloseBody(resp.body) + + if err := checkRespCode(resp.statusCode, []int{expectedStatus}); err != nil { + return nil, err + } + + return resp.headers, nil +} + +// LeaseOptions includes options for all operations regarding leasing blobs +type LeaseOptions struct { + Timeout uint + Origin string `header:"Origin"` + IfMatch string `header:"If-Match"` + IfNoneMatch string `header:"If-None-Match"` + IfModifiedSince *time.Time `header:"If-Modified-Since"` + IfUnmodifiedSince *time.Time `header:"If-Unmodified-Since"` + RequestID string `header:"x-ms-client-request-id"` +} + +// AcquireLease creates a lease for a blob +// returns leaseID acquired +// In API Versions starting on 2012-02-12, the minimum leaseTimeInSeconds is 15, the maximum +// non-infinite leaseTimeInSeconds is 60. To specify an infinite lease, provide the value -1. +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Lease-Blob +func (b *Blob) AcquireLease(leaseTimeInSeconds int, proposedLeaseID string, options *LeaseOptions) (returnedLeaseID string, err error) { + headers := b.Container.bsc.client.getStandardHeaders() + headers[leaseAction] = acquireLease + + if leaseTimeInSeconds == -1 { + // Do nothing, but don't trigger the following clauses. + } else if leaseTimeInSeconds > 60 || b.Container.bsc.client.apiVersion < "2012-02-12" { + leaseTimeInSeconds = 60 + } else if leaseTimeInSeconds < 15 { + leaseTimeInSeconds = 15 + } + + headers[leaseDuration] = strconv.Itoa(leaseTimeInSeconds) + + if proposedLeaseID != "" { + headers[leaseProposedID] = proposedLeaseID + } + + respHeaders, err := b.leaseCommonPut(headers, http.StatusCreated, options) + if err != nil { + return "", err + } + + returnedLeaseID = respHeaders.Get(http.CanonicalHeaderKey(headerLeaseID)) + + if returnedLeaseID != "" { + return returnedLeaseID, nil + } + + return "", errors.New("LeaseID not returned") +} + +// BreakLease breaks the lease for a blob +// Returns the timeout remaining in the lease in seconds +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Lease-Blob +func (b *Blob) BreakLease(options *LeaseOptions) (breakTimeout int, err error) { + headers := b.Container.bsc.client.getStandardHeaders() + headers[leaseAction] = breakLease + return b.breakLeaseCommon(headers, options) +} + +// BreakLeaseWithBreakPeriod breaks the lease for a blob +// breakPeriodInSeconds is used to determine how long until new lease can be created. +// Returns the timeout remaining in the lease in seconds +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Lease-Blob +func (b *Blob) BreakLeaseWithBreakPeriod(breakPeriodInSeconds int, options *LeaseOptions) (breakTimeout int, err error) { + headers := b.Container.bsc.client.getStandardHeaders() + headers[leaseAction] = breakLease + headers[leaseBreakPeriod] = strconv.Itoa(breakPeriodInSeconds) + return b.breakLeaseCommon(headers, options) +} + +// breakLeaseCommon is common code for both version of BreakLease (with and without break period) +func (b *Blob) breakLeaseCommon(headers map[string]string, options *LeaseOptions) (breakTimeout int, err error) { + + respHeaders, err := b.leaseCommonPut(headers, http.StatusAccepted, options) + if err != nil { + return 0, err + } + + breakTimeoutStr := respHeaders.Get(http.CanonicalHeaderKey(leaseTime)) + if breakTimeoutStr != "" { + breakTimeout, err = strconv.Atoi(breakTimeoutStr) + if err != nil { + return 0, err + } + } + + return breakTimeout, nil +} + +// ChangeLease changes a lease ID for a blob +// Returns the new LeaseID acquired +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Lease-Blob +func (b *Blob) ChangeLease(currentLeaseID string, proposedLeaseID string, options *LeaseOptions) (newLeaseID string, err error) { + headers := b.Container.bsc.client.getStandardHeaders() + headers[leaseAction] = changeLease + headers[headerLeaseID] = currentLeaseID + headers[leaseProposedID] = proposedLeaseID + + respHeaders, err := b.leaseCommonPut(headers, http.StatusOK, options) + if err != nil { + return "", err + } + + newLeaseID = respHeaders.Get(http.CanonicalHeaderKey(headerLeaseID)) + if newLeaseID != "" { + return newLeaseID, nil + } + + return "", errors.New("LeaseID not returned") +} + +// ReleaseLease releases the lease for a blob +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Lease-Blob +func (b *Blob) ReleaseLease(currentLeaseID string, options *LeaseOptions) error { + headers := b.Container.bsc.client.getStandardHeaders() + headers[leaseAction] = releaseLease + headers[headerLeaseID] = currentLeaseID + + _, err := b.leaseCommonPut(headers, http.StatusOK, options) + if err != nil { + return err + } + + return nil +} + +// RenewLease renews the lease for a blob as per https://msdn.microsoft.com/en-us/library/azure/ee691972.aspx +func (b *Blob) RenewLease(currentLeaseID string, options *LeaseOptions) error { + headers := b.Container.bsc.client.getStandardHeaders() + headers[leaseAction] = renewLease + headers[headerLeaseID] = currentLeaseID + + _, err := b.leaseCommonPut(headers, http.StatusOK, options) + if err != nil { + return err + } + + return nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/message.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/message.go new file mode 100644 index 000000000000..3ededcd421aa --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/message.go @@ -0,0 +1,153 @@ +package storage + +import ( + "encoding/xml" + "fmt" + "net/http" + "net/url" + "strconv" + "time" +) + +// Message represents an Azure message. +type Message struct { + Queue *Queue + Text string `xml:"MessageText"` + ID string `xml:"MessageId"` + Insertion TimeRFC1123 `xml:"InsertionTime"` + Expiration TimeRFC1123 `xml:"ExpirationTime"` + PopReceipt string `xml:"PopReceipt"` + NextVisible TimeRFC1123 `xml:"TimeNextVisible"` + DequeueCount int `xml:"DequeueCount"` +} + +func (m *Message) buildPath() string { + return fmt.Sprintf("%s/%s", m.Queue.buildPathMessages(), m.ID) +} + +// PutMessageOptions is the set of options can be specified for Put Messsage +// operation. A zero struct does not use any preferences for the request. +type PutMessageOptions struct { + Timeout uint + VisibilityTimeout int + MessageTTL int + RequestID string `header:"x-ms-client-request-id"` +} + +// Put operation adds a new message to the back of the message queue. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Put-Message +func (m *Message) Put(options *PutMessageOptions) error { + query := url.Values{} + headers := m.Queue.qsc.client.getStandardHeaders() + + req := putMessageRequest{MessageText: m.Text} + body, nn, err := xmlMarshal(req) + if err != nil { + return err + } + headers["Content-Length"] = strconv.Itoa(nn) + + if options != nil { + if options.VisibilityTimeout != 0 { + query.Set("visibilitytimeout", strconv.Itoa(options.VisibilityTimeout)) + } + if options.MessageTTL != 0 { + query.Set("messagettl", strconv.Itoa(options.MessageTTL)) + } + query = addTimeout(query, options.Timeout) + headers = mergeHeaders(headers, headersFromStruct(*options)) + } + + uri := m.Queue.qsc.client.getEndpoint(queueServiceName, m.Queue.buildPathMessages(), query) + resp, err := m.Queue.qsc.client.exec(http.MethodPost, uri, headers, body, m.Queue.qsc.auth) + if err != nil { + return err + } + defer readAndCloseBody(resp.body) + + err = xmlUnmarshal(resp.body, m) + if err != nil { + return err + } + return checkRespCode(resp.statusCode, []int{http.StatusCreated}) +} + +// UpdateMessageOptions is the set of options can be specified for Update Messsage +// operation. A zero struct does not use any preferences for the request. +type UpdateMessageOptions struct { + Timeout uint + VisibilityTimeout int + RequestID string `header:"x-ms-client-request-id"` +} + +// Update operation updates the specified message. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Update-Message +func (m *Message) Update(options *UpdateMessageOptions) error { + query := url.Values{} + if m.PopReceipt != "" { + query.Set("popreceipt", m.PopReceipt) + } + + headers := m.Queue.qsc.client.getStandardHeaders() + req := putMessageRequest{MessageText: m.Text} + body, nn, err := xmlMarshal(req) + if err != nil { + return err + } + headers["Content-Length"] = strconv.Itoa(nn) + + if options != nil { + if options.VisibilityTimeout != 0 { + query.Set("visibilitytimeout", strconv.Itoa(options.VisibilityTimeout)) + } + query = addTimeout(query, options.Timeout) + headers = mergeHeaders(headers, headersFromStruct(*options)) + } + uri := m.Queue.qsc.client.getEndpoint(queueServiceName, m.buildPath(), query) + + resp, err := m.Queue.qsc.client.exec(http.MethodPut, uri, headers, body, m.Queue.qsc.auth) + if err != nil { + return err + } + defer readAndCloseBody(resp.body) + + m.PopReceipt = resp.headers.Get("x-ms-popreceipt") + nextTimeStr := resp.headers.Get("x-ms-time-next-visible") + if nextTimeStr != "" { + nextTime, err := time.Parse(time.RFC1123, nextTimeStr) + if err != nil { + return err + } + m.NextVisible = TimeRFC1123(nextTime) + } + + return checkRespCode(resp.statusCode, []int{http.StatusNoContent}) +} + +// Delete operation deletes the specified message. +// +// See https://msdn.microsoft.com/en-us/library/azure/dd179347.aspx +func (m *Message) Delete(options *QueueServiceOptions) error { + params := url.Values{"popreceipt": {m.PopReceipt}} + headers := m.Queue.qsc.client.getStandardHeaders() + + if options != nil { + params = addTimeout(params, options.Timeout) + headers = mergeHeaders(headers, headersFromStruct(*options)) + } + uri := m.Queue.qsc.client.getEndpoint(queueServiceName, m.buildPath(), params) + + resp, err := m.Queue.qsc.client.exec(http.MethodDelete, uri, headers, nil, m.Queue.qsc.auth) + if err != nil { + return err + } + readAndCloseBody(resp.body) + return checkRespCode(resp.statusCode, []int{http.StatusNoContent}) +} + +type putMessageRequest struct { + XMLName xml.Name `xml:"QueueMessage"` + MessageText string `xml:"MessageText"` +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/odata.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/odata.go new file mode 100644 index 000000000000..41d832e2be11 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/odata.go @@ -0,0 +1,33 @@ +package storage + +// MetadataLevel determines if operations should return a paylod, +// and it level of detail. +type MetadataLevel string + +// This consts are meant to help with Odata supported operations +const ( + OdataTypeSuffix = "@odata.type" + + // Types + + OdataBinary = "Edm.Binary" + OdataDateTime = "Edm.DateTime" + OdataGUID = "Edm.Guid" + OdataInt64 = "Edm.Int64" + + // Query options + + OdataFilter = "$filter" + OdataOrderBy = "$orderby" + OdataTop = "$top" + OdataSkip = "$skip" + OdataCount = "$count" + OdataExpand = "$expand" + OdataSelect = "$select" + OdataSearch = "$search" + + EmptyPayload MetadataLevel = "" + NoMetadata MetadataLevel = "application/json;odata=nometadata" + MinimalMetadata MetadataLevel = "application/json;odata=minimalmetadata" + FullMetadata MetadataLevel = "application/json;odata=fullmetadata" +) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/pageblob.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/pageblob.go new file mode 100644 index 000000000000..bc5b398d3ff8 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/pageblob.go @@ -0,0 +1,189 @@ +package storage + +import ( + "encoding/xml" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "time" +) + +// GetPageRangesResponse contains the response fields from +// Get Page Ranges call. +// +// See https://msdn.microsoft.com/en-us/library/azure/ee691973.aspx +type GetPageRangesResponse struct { + XMLName xml.Name `xml:"PageList"` + PageList []PageRange `xml:"PageRange"` +} + +// PageRange contains information about a page of a page blob from +// Get Pages Range call. +// +// See https://msdn.microsoft.com/en-us/library/azure/ee691973.aspx +type PageRange struct { + Start int64 `xml:"Start"` + End int64 `xml:"End"` +} + +var ( + errBlobCopyAborted = errors.New("storage: blob copy is aborted") + errBlobCopyIDMismatch = errors.New("storage: blob copy id is a mismatch") +) + +// PutPageOptions includes the options for a put page operation +type PutPageOptions struct { + Timeout uint + LeaseID string `header:"x-ms-lease-id"` + IfSequenceNumberLessThanOrEqualTo *int `header:"x-ms-if-sequence-number-le"` + IfSequenceNumberLessThan *int `header:"x-ms-if-sequence-number-lt"` + IfSequenceNumberEqualTo *int `header:"x-ms-if-sequence-number-eq"` + IfModifiedSince *time.Time `header:"If-Modified-Since"` + IfUnmodifiedSince *time.Time `header:"If-Unmodified-Since"` + IfMatch string `header:"If-Match"` + IfNoneMatch string `header:"If-None-Match"` + RequestID string `header:"x-ms-client-request-id"` +} + +// WriteRange writes a range of pages to a page blob. +// Ranges must be aligned with 512-byte boundaries and chunk must be of size +// multiplies by 512. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Put-Page +func (b *Blob) WriteRange(blobRange BlobRange, bytes io.Reader, options *PutPageOptions) error { + if bytes == nil { + return errors.New("bytes cannot be nil") + } + return b.modifyRange(blobRange, bytes, options) +} + +// ClearRange clears the given range in a page blob. +// Ranges must be aligned with 512-byte boundaries and chunk must be of size +// multiplies by 512. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Put-Page +func (b *Blob) ClearRange(blobRange BlobRange, options *PutPageOptions) error { + return b.modifyRange(blobRange, nil, options) +} + +func (b *Blob) modifyRange(blobRange BlobRange, bytes io.Reader, options *PutPageOptions) error { + if blobRange.End < blobRange.Start { + return errors.New("the value for rangeEnd must be greater than or equal to rangeStart") + } + if blobRange.Start%512 != 0 { + return errors.New("the value for rangeStart must be a modulus of 512") + } + if blobRange.End%512 != 511 { + return errors.New("the value for rangeEnd must be a modulus of 511") + } + + params := url.Values{"comp": {"page"}} + + // default to clear + write := "clear" + var cl uint64 + + // if bytes is not nil then this is an update operation + if bytes != nil { + write = "update" + cl = (blobRange.End - blobRange.Start) + 1 + } + + headers := b.Container.bsc.client.getStandardHeaders() + headers["x-ms-blob-type"] = string(BlobTypePage) + headers["x-ms-page-write"] = write + headers["x-ms-range"] = blobRange.String() + headers["Content-Length"] = fmt.Sprintf("%v", cl) + + if options != nil { + params = addTimeout(params, options.Timeout) + headers = mergeHeaders(headers, headersFromStruct(*options)) + } + uri := b.Container.bsc.client.getEndpoint(blobServiceName, b.buildPath(), params) + + resp, err := b.Container.bsc.client.exec(http.MethodPut, uri, headers, bytes, b.Container.bsc.auth) + if err != nil { + return err + } + readAndCloseBody(resp.body) + + return checkRespCode(resp.statusCode, []int{http.StatusCreated}) +} + +// GetPageRangesOptions includes the options for a get page ranges operation +type GetPageRangesOptions struct { + Timeout uint + Snapshot *time.Time + PreviousSnapshot *time.Time + Range *BlobRange + LeaseID string `header:"x-ms-lease-id"` + RequestID string `header:"x-ms-client-request-id"` +} + +// GetPageRanges returns the list of valid page ranges for a page blob. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Get-Page-Ranges +func (b *Blob) GetPageRanges(options *GetPageRangesOptions) (GetPageRangesResponse, error) { + params := url.Values{"comp": {"pagelist"}} + headers := b.Container.bsc.client.getStandardHeaders() + + if options != nil { + params = addTimeout(params, options.Timeout) + params = addSnapshot(params, options.Snapshot) + if options.PreviousSnapshot != nil { + params.Add("prevsnapshot", timeRfc1123Formatted(*options.PreviousSnapshot)) + } + if options.Range != nil { + headers["Range"] = options.Range.String() + } + headers = mergeHeaders(headers, headersFromStruct(*options)) + } + uri := b.Container.bsc.client.getEndpoint(blobServiceName, b.buildPath(), params) + + var out GetPageRangesResponse + resp, err := b.Container.bsc.client.exec(http.MethodGet, uri, headers, nil, b.Container.bsc.auth) + if err != nil { + return out, err + } + defer resp.body.Close() + + if err = checkRespCode(resp.statusCode, []int{http.StatusOK}); err != nil { + return out, err + } + err = xmlUnmarshal(resp.body, &out) + return out, err +} + +// PutPageBlob initializes an empty page blob with specified name and maximum +// size in bytes (size must be aligned to a 512-byte boundary). A page blob must +// be created using this method before writing pages. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Put-Blob +func (b *Blob) PutPageBlob(options *PutBlobOptions) error { + if b.Properties.ContentLength%512 != 0 { + return errors.New("Content length must be aligned to a 512-byte boundary") + } + + params := url.Values{} + headers := b.Container.bsc.client.getStandardHeaders() + headers["x-ms-blob-type"] = string(BlobTypePage) + headers["x-ms-blob-content-length"] = fmt.Sprintf("%v", b.Properties.ContentLength) + headers["x-ms-blob-sequence-number"] = fmt.Sprintf("%v", b.Properties.SequenceNumber) + headers = mergeHeaders(headers, headersFromStruct(b.Properties)) + headers = b.Container.bsc.client.addMetadataToHeaders(headers, b.Metadata) + + if options != nil { + params = addTimeout(params, options.Timeout) + headers = mergeHeaders(headers, headersFromStruct(*options)) + } + uri := b.Container.bsc.client.getEndpoint(blobServiceName, b.buildPath(), params) + + resp, err := b.Container.bsc.client.exec(http.MethodPut, uri, headers, nil, b.Container.bsc.auth) + if err != nil { + return err + } + readAndCloseBody(resp.body) + return checkRespCode(resp.statusCode, []int{http.StatusCreated}) +} 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 0cd3578442ea..c2c7f742c452 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 @@ -2,166 +2,139 @@ package storage import ( "encoding/xml" + "errors" "fmt" + "io" "net/http" "net/url" "strconv" - "strings" + "time" ) const ( // casing is per Golang's http.Header canonicalizing the header names. - approximateMessagesCountHeader = "X-Ms-Approximate-Messages-Count" - userDefinedMetadataHeaderPrefix = "X-Ms-Meta-" + approximateMessagesCountHeader = "X-Ms-Approximate-Messages-Count" ) -// QueueServiceClient contains operations for Microsoft Azure Queue Storage -// Service. -type QueueServiceClient struct { - client Client +// QueueAccessPolicy represents each access policy in the queue ACL. +type QueueAccessPolicy struct { + ID string + StartTime time.Time + ExpiryTime time.Time + CanRead bool + CanAdd bool + CanUpdate bool + CanProcess bool } -func pathForQueue(queue string) string { return fmt.Sprintf("/%s", queue) } -func pathForQueueMessages(queue string) string { return fmt.Sprintf("/%s/messages", queue) } -func pathForMessage(queue, name string) string { return fmt.Sprintf("/%s/messages/%s", queue, name) } - -type putMessageRequest struct { - XMLName xml.Name `xml:"QueueMessage"` - MessageText string `xml:"MessageText"` +// QueuePermissions represents the queue ACLs. +type QueuePermissions struct { + AccessPolicies []QueueAccessPolicy } -// PutMessageParameters is the set of options can be specified for Put Messsage -// operation. A zero struct does not use any preferences for the request. -type PutMessageParameters struct { - VisibilityTimeout int - MessageTTL int +// SetQueuePermissionOptions includes options for a set queue permissions operation +type SetQueuePermissionOptions struct { + Timeout uint + RequestID string `header:"x-ms-client-request-id"` } -func (p PutMessageParameters) getParameters() url.Values { - out := url.Values{} - if p.VisibilityTimeout != 0 { - out.Set("visibilitytimeout", strconv.Itoa(p.VisibilityTimeout)) - } - if p.MessageTTL != 0 { - out.Set("messagettl", strconv.Itoa(p.MessageTTL)) - } - return out +// Queue represents an Azure queue. +type Queue struct { + qsc *QueueServiceClient + Name string + Metadata map[string]string + AproxMessageCount uint64 } -// GetMessagesParameters is the set of options can be specified for Get -// Messsages operation. A zero struct does not use any preferences for the -// request. -type GetMessagesParameters struct { - NumOfMessages int - VisibilityTimeout int +func (q *Queue) buildPath() string { + return fmt.Sprintf("/%s", q.Name) } -func (p GetMessagesParameters) getParameters() url.Values { - out := url.Values{} - if p.NumOfMessages != 0 { - out.Set("numofmessages", strconv.Itoa(p.NumOfMessages)) - } - if p.VisibilityTimeout != 0 { - out.Set("visibilitytimeout", strconv.Itoa(p.VisibilityTimeout)) - } - return out +func (q *Queue) buildPathMessages() string { + return fmt.Sprintf("%s/messages", q.buildPath()) } -// PeekMessagesParameters is the set of options can be specified for Peek -// Messsage operation. A zero struct does not use any preferences for the -// request. -type PeekMessagesParameters struct { - NumOfMessages int +// QueueServiceOptions includes options for some queue service operations +type QueueServiceOptions struct { + Timeout uint + RequestID string `header:"x-ms-client-request-id"` } -func (p PeekMessagesParameters) getParameters() url.Values { - out := url.Values{"peekonly": {"true"}} // Required for peek operation - if p.NumOfMessages != 0 { - out.Set("numofmessages", strconv.Itoa(p.NumOfMessages)) +// Create operation creates a queue under the given account. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Create-Queue4 +func (q *Queue) Create(options *QueueServiceOptions) error { + params := url.Values{} + headers := q.qsc.client.getStandardHeaders() + headers = q.qsc.client.addMetadataToHeaders(headers, q.Metadata) + + if options != nil { + params = addTimeout(params, options.Timeout) + headers = mergeHeaders(headers, headersFromStruct(*options)) } - return out -} + uri := q.qsc.client.getEndpoint(queueServiceName, q.buildPath(), params) -// UpdateMessageParameters is the set of options can be specified for Update Messsage -// operation. A zero struct does not use any preferences for the request. -type UpdateMessageParameters struct { - PopReceipt string - VisibilityTimeout int + resp, err := q.qsc.client.exec(http.MethodPut, uri, headers, nil, q.qsc.auth) + if err != nil { + return err + } + readAndCloseBody(resp.body) + return checkRespCode(resp.statusCode, []int{http.StatusCreated}) } -func (p UpdateMessageParameters) getParameters() url.Values { - out := url.Values{} - if p.PopReceipt != "" { - out.Set("popreceipt", p.PopReceipt) +// Delete operation permanently deletes the specified queue. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Delete-Queue3 +func (q *Queue) Delete(options *QueueServiceOptions) error { + params := url.Values{} + headers := q.qsc.client.getStandardHeaders() + + if options != nil { + params = addTimeout(params, options.Timeout) + headers = mergeHeaders(headers, headersFromStruct(*options)) } - if p.VisibilityTimeout != 0 { - out.Set("visibilitytimeout", strconv.Itoa(p.VisibilityTimeout)) + uri := q.qsc.client.getEndpoint(queueServiceName, q.buildPath(), params) + resp, err := q.qsc.client.exec(http.MethodDelete, uri, headers, nil, q.qsc.auth) + if err != nil { + return err } - return out -} - -// GetMessagesResponse represents a response returned from Get Messages -// operation. -type GetMessagesResponse struct { - XMLName xml.Name `xml:"QueueMessagesList"` - QueueMessagesList []GetMessageResponse `xml:"QueueMessage"` -} - -// GetMessageResponse represents a QueueMessage object returned from Get -// Messages operation response. -type GetMessageResponse struct { - MessageID string `xml:"MessageId"` - InsertionTime string `xml:"InsertionTime"` - ExpirationTime string `xml:"ExpirationTime"` - PopReceipt string `xml:"PopReceipt"` - TimeNextVisible string `xml:"TimeNextVisible"` - DequeueCount int `xml:"DequeueCount"` - MessageText string `xml:"MessageText"` -} - -// PeekMessagesResponse represents a response returned from Get Messages -// operation. -type PeekMessagesResponse struct { - XMLName xml.Name `xml:"QueueMessagesList"` - QueueMessagesList []PeekMessageResponse `xml:"QueueMessage"` -} - -// PeekMessageResponse represents a QueueMessage object returned from Peek -// Messages operation response. -type PeekMessageResponse struct { - MessageID string `xml:"MessageId"` - InsertionTime string `xml:"InsertionTime"` - ExpirationTime string `xml:"ExpirationTime"` - DequeueCount int `xml:"DequeueCount"` - MessageText string `xml:"MessageText"` + readAndCloseBody(resp.body) + return checkRespCode(resp.statusCode, []int{http.StatusNoContent}) } -// QueueMetadataResponse represents user defined metadata and queue -// properties on a specific queue. -// -// See https://msdn.microsoft.com/en-us/library/azure/dd179384.aspx -type QueueMetadataResponse struct { - ApproximateMessageCount int - UserDefinedMetadata map[string]string +// Exists returns true if a queue with given name exists. +func (q *Queue) Exists() (bool, error) { + uri := q.qsc.client.getEndpoint(queueServiceName, q.buildPath(), url.Values{"comp": {"metadata"}}) + resp, err := q.qsc.client.exec(http.MethodGet, uri, q.qsc.client.getStandardHeaders(), nil, q.qsc.auth) + if resp != nil { + defer readAndCloseBody(resp.body) + if resp.statusCode == http.StatusOK || resp.statusCode == http.StatusNotFound { + return resp.statusCode == http.StatusOK, nil + } + } + return false, err } // SetMetadata operation sets user-defined metadata on the specified queue. // Metadata is associated with the queue as name-value pairs. // -// See https://msdn.microsoft.com/en-us/library/azure/dd179348.aspx -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() - for k, v := range metadata { - headers[userDefinedMetadataHeaderPrefix+k] = v +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Set-Queue-Metadata +func (q *Queue) SetMetadata(options *QueueServiceOptions) error { + params := url.Values{"comp": {"metadata"}} + headers := q.qsc.client.getStandardHeaders() + headers = q.qsc.client.addMetadataToHeaders(headers, q.Metadata) + + if options != nil { + params = addTimeout(params, options.Timeout) + headers = mergeHeaders(headers, headersFromStruct(*options)) } + uri := q.qsc.client.getEndpoint(queueServiceName, q.buildPath(), params) - resp, err := c.client.exec("PUT", uri, headers, nil) + resp, err := q.qsc.client.exec(http.MethodPut, uri, headers, nil, q.qsc.auth) if err != nil { return err } - defer resp.body.Close() - + readAndCloseBody(resp.body) return checkRespCode(resp.statusCode, []int{http.StatusNoContent}) } @@ -169,176 +142,286 @@ func (c QueueServiceClient) SetMetadata(name string, metadata map[string]string) // properties on the specified queue. Metadata is associated with // the queue as name-values pairs. // -// See https://msdn.microsoft.com/en-us/library/azure/dd179384.aspx +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Set-Queue-Metadata // // Because the way Golang's http client (and http.Header in particular) // canonicalize header names, the returned metadata names would always // be all lower case. -func (c QueueServiceClient) GetMetadata(name string) (QueueMetadataResponse, error) { - qm := QueueMetadataResponse{} - qm.UserDefinedMetadata = make(map[string]string) - uri := c.client.getEndpoint(queueServiceName, pathForQueue(name), url.Values{"comp": []string{"metadata"}}) - headers := c.client.getStandardHeaders() - resp, err := c.client.exec("GET", uri, headers, nil) - if err != nil { - return qm, err +func (q *Queue) GetMetadata(options *QueueServiceOptions) error { + params := url.Values{"comp": {"metadata"}} + headers := q.qsc.client.getStandardHeaders() + + if options != nil { + params = addTimeout(params, options.Timeout) + headers = mergeHeaders(headers, headersFromStruct(*options)) } - defer resp.body.Close() + uri := q.qsc.client.getEndpoint(queueServiceName, q.buildPath(), url.Values{"comp": {"metadata"}}) - for k, v := range resp.headers { - if len(v) != 1 { - return qm, fmt.Errorf("Unexpected number of values (%d) in response header '%s'", len(v), k) - } + resp, err := q.qsc.client.exec(http.MethodGet, uri, headers, nil, q.qsc.auth) + if err != nil { + return err + } + defer readAndCloseBody(resp.body) - value := v[0] + if err := checkRespCode(resp.statusCode, []int{http.StatusOK}); err != nil { + return err + } - if k == approximateMessagesCountHeader { - qm.ApproximateMessageCount, err = strconv.Atoi(value) - if err != nil { - return qm, fmt.Errorf("Unexpected value in response header '%s': '%s' ", k, value) - } - } else if strings.HasPrefix(k, userDefinedMetadataHeaderPrefix) { - name := strings.TrimPrefix(k, userDefinedMetadataHeaderPrefix) - qm.UserDefinedMetadata[strings.ToLower(name)] = value + aproxMessagesStr := resp.headers.Get(http.CanonicalHeaderKey(approximateMessagesCountHeader)) + if aproxMessagesStr != "" { + aproxMessages, err := strconv.ParseUint(aproxMessagesStr, 10, 64) + if err != nil { + return err } + q.AproxMessageCount = aproxMessages } - return qm, checkRespCode(resp.statusCode, []int{http.StatusOK}) + q.Metadata = getMetadataFromHeaders(resp.headers) + return nil } -// CreateQueue operation creates a queue under the given account. -// -// See https://msdn.microsoft.com/en-us/library/azure/dd179342.aspx -func (c QueueServiceClient) CreateQueue(name string) error { - uri := c.client.getEndpoint(queueServiceName, pathForQueue(name), url.Values{}) - headers := c.client.getStandardHeaders() - resp, err := c.client.exec("PUT", uri, headers, nil) - if err != nil { - return err +// GetMessageReference returns a message object with the specified text. +func (q *Queue) GetMessageReference(text string) *Message { + return &Message{ + Queue: q, + Text: text, } - defer resp.body.Close() - return checkRespCode(resp.statusCode, []int{http.StatusCreated}) } -// DeleteQueue operation permanently deletes the specified queue. +// GetMessagesOptions is the set of options can be specified for Get +// Messsages operation. A zero struct does not use any preferences for the +// request. +type GetMessagesOptions struct { + Timeout uint + NumOfMessages int + VisibilityTimeout int + RequestID string `header:"x-ms-client-request-id"` +} + +type messages struct { + XMLName xml.Name `xml:"QueueMessagesList"` + Messages []Message `xml:"QueueMessage"` +} + +// GetMessages operation retrieves one or more messages from the front of the +// queue. // -// See https://msdn.microsoft.com/en-us/library/azure/dd179436.aspx -func (c QueueServiceClient) DeleteQueue(name string) error { - uri := c.client.getEndpoint(queueServiceName, pathForQueue(name), url.Values{}) - resp, err := c.client.exec("DELETE", uri, c.client.getStandardHeaders(), nil) +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Get-Messages +func (q *Queue) GetMessages(options *GetMessagesOptions) ([]Message, error) { + query := url.Values{} + headers := q.qsc.client.getStandardHeaders() + + if options != nil { + if options.NumOfMessages != 0 { + query.Set("numofmessages", strconv.Itoa(options.NumOfMessages)) + } + if options.VisibilityTimeout != 0 { + query.Set("visibilitytimeout", strconv.Itoa(options.VisibilityTimeout)) + } + query = addTimeout(query, options.Timeout) + headers = mergeHeaders(headers, headersFromStruct(*options)) + } + uri := q.qsc.client.getEndpoint(queueServiceName, q.buildPathMessages(), query) + + resp, err := q.qsc.client.exec(http.MethodGet, uri, headers, nil, q.qsc.auth) if err != nil { - return err + return []Message{}, err } - defer resp.body.Close() - return checkRespCode(resp.statusCode, []int{http.StatusNoContent}) -} + defer readAndCloseBody(resp.body) -// QueueExists returns true if a queue with given name exists. -func (c QueueServiceClient) QueueExists(name string) (bool, error) { - uri := c.client.getEndpoint(queueServiceName, pathForQueue(name), url.Values{"comp": {"metadata"}}) - resp, err := c.client.exec("GET", uri, c.client.getStandardHeaders(), nil) - if resp != nil && (resp.statusCode == http.StatusOK || resp.statusCode == http.StatusNotFound) { - return resp.statusCode == http.StatusOK, nil + var out messages + err = xmlUnmarshal(resp.body, &out) + if err != nil { + return []Message{}, err + } + for i := range out.Messages { + out.Messages[i].Queue = q } + return out.Messages, err +} - return false, err +// PeekMessagesOptions is the set of options can be specified for Peek +// Messsage operation. A zero struct does not use any preferences for the +// request. +type PeekMessagesOptions struct { + Timeout uint + NumOfMessages int + RequestID string `header:"x-ms-client-request-id"` } -// PutMessage operation adds a new message to the back of the message queue. +// PeekMessages retrieves one or more messages from the front of the queue, but +// does not alter the visibility of the message. // -// See https://msdn.microsoft.com/en-us/library/azure/dd179346.aspx -func (c QueueServiceClient) PutMessage(queue string, message string, params PutMessageParameters) error { - uri := c.client.getEndpoint(queueServiceName, pathForQueueMessages(queue), params.getParameters()) - req := putMessageRequest{MessageText: message} - body, nn, err := xmlMarshal(req) +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Peek-Messages +func (q *Queue) PeekMessages(options *PeekMessagesOptions) ([]Message, error) { + query := url.Values{"peekonly": {"true"}} // Required for peek operation + headers := q.qsc.client.getStandardHeaders() + + if options != nil { + if options.NumOfMessages != 0 { + query.Set("numofmessages", strconv.Itoa(options.NumOfMessages)) + } + query = addTimeout(query, options.Timeout) + headers = mergeHeaders(headers, headersFromStruct(*options)) + } + uri := q.qsc.client.getEndpoint(queueServiceName, q.buildPathMessages(), query) + + resp, err := q.qsc.client.exec(http.MethodGet, uri, headers, nil, q.qsc.auth) if err != nil { - return err + return []Message{}, err } - headers := c.client.getStandardHeaders() - headers["Content-Length"] = strconv.Itoa(nn) - resp, err := c.client.exec("POST", uri, headers, body) + defer readAndCloseBody(resp.body) + + var out messages + err = xmlUnmarshal(resp.body, &out) if err != nil { - return err + return []Message{}, err } - defer resp.body.Close() - return checkRespCode(resp.statusCode, []int{http.StatusCreated}) + for i := range out.Messages { + out.Messages[i].Queue = q + } + return out.Messages, err } // ClearMessages operation deletes all messages from the specified queue. // -// See https://msdn.microsoft.com/en-us/library/azure/dd179454.aspx -func (c QueueServiceClient) ClearMessages(queue string) error { - uri := c.client.getEndpoint(queueServiceName, pathForQueueMessages(queue), url.Values{}) - resp, err := c.client.exec("DELETE", uri, c.client.getStandardHeaders(), nil) +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Clear-Messages +func (q *Queue) ClearMessages(options *QueueServiceOptions) error { + params := url.Values{} + headers := q.qsc.client.getStandardHeaders() + + if options != nil { + params = addTimeout(params, options.Timeout) + headers = mergeHeaders(headers, headersFromStruct(*options)) + } + uri := q.qsc.client.getEndpoint(queueServiceName, q.buildPathMessages(), params) + + resp, err := q.qsc.client.exec(http.MethodDelete, uri, headers, nil, q.qsc.auth) if err != nil { return err } - defer resp.body.Close() + readAndCloseBody(resp.body) return checkRespCode(resp.statusCode, []int{http.StatusNoContent}) } -// GetMessages operation retrieves one or more messages from the front of the -// queue. -// -// See https://msdn.microsoft.com/en-us/library/azure/dd179474.aspx -func (c QueueServiceClient) GetMessages(queue string, params GetMessagesParameters) (GetMessagesResponse, error) { - var r GetMessagesResponse - uri := c.client.getEndpoint(queueServiceName, pathForQueueMessages(queue), params.getParameters()) - resp, err := c.client.exec("GET", uri, c.client.getStandardHeaders(), nil) +// SetPermissions sets up queue permissions +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/set-queue-acl +func (q *Queue) SetPermissions(permissions QueuePermissions, options *SetQueuePermissionOptions) error { + body, length, err := generateQueueACLpayload(permissions.AccessPolicies) if err != nil { - return r, err + return err } - defer resp.body.Close() - err = xmlUnmarshal(resp.body, &r) - return r, err -} -// PeekMessages retrieves one or more messages from the front of the queue, but -// does not alter the visibility of the message. -// -// See https://msdn.microsoft.com/en-us/library/azure/dd179472.aspx -func (c QueueServiceClient) PeekMessages(queue string, params PeekMessagesParameters) (PeekMessagesResponse, error) { - var r PeekMessagesResponse - uri := c.client.getEndpoint(queueServiceName, pathForQueueMessages(queue), params.getParameters()) - resp, err := c.client.exec("GET", uri, c.client.getStandardHeaders(), nil) - if err != nil { - return r, err + params := url.Values{ + "comp": {"acl"}, } - defer resp.body.Close() - err = xmlUnmarshal(resp.body, &r) - return r, err -} + headers := q.qsc.client.getStandardHeaders() + headers["Content-Length"] = strconv.Itoa(length) -// DeleteMessage operation deletes the specified message. -// -// See https://msdn.microsoft.com/en-us/library/azure/dd179347.aspx -func (c QueueServiceClient) DeleteMessage(queue, messageID, popReceipt string) error { - uri := c.client.getEndpoint(queueServiceName, pathForMessage(queue, messageID), url.Values{ - "popreceipt": {popReceipt}}) - resp, err := c.client.exec("DELETE", uri, c.client.getStandardHeaders(), nil) + if options != nil { + params = addTimeout(params, options.Timeout) + headers = mergeHeaders(headers, headersFromStruct(*options)) + } + uri := q.qsc.client.getEndpoint(queueServiceName, q.buildPath(), params) + resp, err := q.qsc.client.exec(http.MethodPut, uri, headers, body, q.qsc.auth) if err != nil { return err } - defer resp.body.Close() - return checkRespCode(resp.statusCode, []int{http.StatusNoContent}) + defer readAndCloseBody(resp.body) + + if err := checkRespCode(resp.statusCode, []int{http.StatusNoContent}); err != nil { + return errors.New("Unable to set permissions") + } + + return nil } -// UpdateMessage operation deletes the specified message. -// -// See https://msdn.microsoft.com/en-us/library/azure/hh452234.aspx -func (c QueueServiceClient) UpdateMessage(queue string, messageID string, message string, params UpdateMessageParameters) error { - uri := c.client.getEndpoint(queueServiceName, pathForMessage(queue, messageID), params.getParameters()) - req := putMessageRequest{MessageText: message} - body, nn, err := xmlMarshal(req) - if err != nil { - return err +func generateQueueACLpayload(policies []QueueAccessPolicy) (io.Reader, int, error) { + sil := SignedIdentifiers{ + SignedIdentifiers: []SignedIdentifier{}, + } + for _, qapd := range policies { + permission := qapd.generateQueuePermissions() + signedIdentifier := convertAccessPolicyToXMLStructs(qapd.ID, qapd.StartTime, qapd.ExpiryTime, permission) + sil.SignedIdentifiers = append(sil.SignedIdentifiers, signedIdentifier) + } + return xmlMarshal(sil) +} + +func (qapd *QueueAccessPolicy) generateQueuePermissions() (permissions string) { + // generate the permissions string (raup). + // still want the end user API to have bool flags. + permissions = "" + + if qapd.CanRead { + permissions += "r" + } + + if qapd.CanAdd { + permissions += "a" + } + + if qapd.CanUpdate { + permissions += "u" + } + + if qapd.CanProcess { + permissions += "p" + } + + return permissions +} + +// GetQueuePermissionOptions includes options for a get queue permissions operation +type GetQueuePermissionOptions struct { + Timeout uint + RequestID string `header:"x-ms-client-request-id"` +} + +// GetPermissions gets the queue permissions as per https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/get-queue-acl +// If timeout is 0 then it will not be passed to Azure +func (q *Queue) GetPermissions(options *GetQueuePermissionOptions) (*QueuePermissions, error) { + params := url.Values{ + "comp": {"acl"}, } - headers := c.client.getStandardHeaders() - headers["Content-Length"] = fmt.Sprintf("%d", nn) - resp, err := c.client.exec("PUT", uri, headers, body) + headers := q.qsc.client.getStandardHeaders() + + if options != nil { + params = addTimeout(params, options.Timeout) + headers = mergeHeaders(headers, headersFromStruct(*options)) + } + uri := q.qsc.client.getEndpoint(queueServiceName, q.buildPath(), params) + resp, err := q.qsc.client.exec(http.MethodGet, uri, headers, nil, q.qsc.auth) if err != nil { - return err + return nil, err } defer resp.body.Close() - return checkRespCode(resp.statusCode, []int{http.StatusNoContent}) + + var ap AccessPolicy + err = xmlUnmarshal(resp.body, &ap.SignedIdentifiersList) + if err != nil { + return nil, err + } + return buildQueueAccessPolicy(ap, &resp.headers), nil +} + +func buildQueueAccessPolicy(ap AccessPolicy, headers *http.Header) *QueuePermissions { + permissions := QueuePermissions{ + AccessPolicies: []QueueAccessPolicy{}, + } + + for _, policy := range ap.SignedIdentifiersList.SignedIdentifiers { + qapd := QueueAccessPolicy{ + ID: policy.ID, + StartTime: policy.AccessPolicy.StartTime, + ExpiryTime: policy.AccessPolicy.ExpiryTime, + } + qapd.CanRead = updatePermissions(policy.AccessPolicy.Permission, "r") + qapd.CanAdd = updatePermissions(policy.AccessPolicy.Permission, "a") + qapd.CanUpdate = updatePermissions(policy.AccessPolicy.Permission, "u") + qapd.CanProcess = updatePermissions(policy.AccessPolicy.Permission, "p") + + permissions.AccessPolicies = append(permissions.AccessPolicies, qapd) + } + return &permissions } diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/queueserviceclient.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/queueserviceclient.go new file mode 100644 index 000000000000..19b44941c8cc --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/queueserviceclient.go @@ -0,0 +1,28 @@ +package storage + +// QueueServiceClient contains operations for Microsoft Azure Queue Storage +// Service. +type QueueServiceClient struct { + client Client + auth authentication +} + +// GetServiceProperties gets the properties of your storage account's queue service. +// See: https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/get-queue-service-properties +func (q *QueueServiceClient) GetServiceProperties() (*ServiceProperties, error) { + return q.client.getServiceProperties(queueServiceName, q.auth) +} + +// SetServiceProperties sets the properties of your storage account's queue service. +// See: https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/set-queue-service-properties +func (q *QueueServiceClient) SetServiceProperties(props ServiceProperties) error { + return q.client.setServiceProperties(props, queueServiceName, q.auth) +} + +// GetQueueReference returns a Container object for the specified queue name. +func (q *QueueServiceClient) GetQueueReference(name string) *Queue { + return &Queue{ + qsc: q, + Name: name, + } +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/share.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/share.go new file mode 100644 index 000000000000..e6a868081a01 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/share.go @@ -0,0 +1,202 @@ +package storage + +import ( + "fmt" + "net/http" + "net/url" + "strconv" +) + +// Share represents an Azure file share. +type Share struct { + fsc *FileServiceClient + Name string `xml:"Name"` + Properties ShareProperties `xml:"Properties"` + Metadata map[string]string +} + +// ShareProperties contains various properties of a share. +type ShareProperties struct { + LastModified string `xml:"Last-Modified"` + Etag string `xml:"Etag"` + Quota int `xml:"Quota"` +} + +// builds the complete path for this share object. +func (s *Share) buildPath() string { + return fmt.Sprintf("/%s", s.Name) +} + +// Create this share under the associated account. +// If a share with the same name already exists, the operation fails. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Create-Share +func (s *Share) Create(options *FileRequestOptions) error { + extraheaders := map[string]string{} + if s.Properties.Quota > 0 { + extraheaders["x-ms-share-quota"] = strconv.Itoa(s.Properties.Quota) + } + + params := prepareOptions(options) + headers, err := s.fsc.createResource(s.buildPath(), resourceShare, params, mergeMDIntoExtraHeaders(s.Metadata, extraheaders), []int{http.StatusCreated}) + if err != nil { + return err + } + + s.updateEtagAndLastModified(headers) + return nil +} + +// CreateIfNotExists creates this share under the associated account if +// it does not exist. Returns true if the share is newly created or false if +// the share already exists. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Create-Share +func (s *Share) CreateIfNotExists(options *FileRequestOptions) (bool, error) { + extraheaders := map[string]string{} + if s.Properties.Quota > 0 { + extraheaders["x-ms-share-quota"] = strconv.Itoa(s.Properties.Quota) + } + + params := prepareOptions(options) + resp, err := s.fsc.createResourceNoClose(s.buildPath(), resourceShare, params, extraheaders) + if resp != nil { + defer readAndCloseBody(resp.body) + if resp.statusCode == http.StatusCreated || resp.statusCode == http.StatusConflict { + if resp.statusCode == http.StatusCreated { + s.updateEtagAndLastModified(resp.headers) + return true, nil + } + return false, s.FetchAttributes(nil) + } + } + + return false, err +} + +// Delete marks this share for deletion. The share along with any files +// and directories contained within it are later deleted during garbage +// collection. If the share does not exist the operation fails +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Delete-Share +func (s *Share) Delete(options *FileRequestOptions) error { + return s.fsc.deleteResource(s.buildPath(), resourceShare, options) +} + +// DeleteIfExists operation marks this share for deletion if it exists. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Delete-Share +func (s *Share) DeleteIfExists(options *FileRequestOptions) (bool, error) { + resp, err := s.fsc.deleteResourceNoClose(s.buildPath(), resourceShare, options) + if resp != nil { + defer readAndCloseBody(resp.body) + if resp.statusCode == http.StatusAccepted || resp.statusCode == http.StatusNotFound { + return resp.statusCode == http.StatusAccepted, nil + } + } + return false, err +} + +// Exists returns true if this share already exists +// on the storage account, otherwise returns false. +func (s *Share) Exists() (bool, error) { + exists, headers, err := s.fsc.resourceExists(s.buildPath(), resourceShare) + if exists { + s.updateEtagAndLastModified(headers) + s.updateQuota(headers) + } + return exists, err +} + +// FetchAttributes retrieves metadata and properties for this share. +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/get-share-properties +func (s *Share) FetchAttributes(options *FileRequestOptions) error { + params := prepareOptions(options) + headers, err := s.fsc.getResourceHeaders(s.buildPath(), compNone, resourceShare, params, http.MethodHead) + if err != nil { + return err + } + + s.updateEtagAndLastModified(headers) + s.updateQuota(headers) + s.Metadata = getMetadataFromHeaders(headers) + + return nil +} + +// GetRootDirectoryReference returns a Directory object at the root of this share. +func (s *Share) GetRootDirectoryReference() *Directory { + return &Directory{ + fsc: s.fsc, + share: s, + } +} + +// ServiceClient returns the FileServiceClient associated with this share. +func (s *Share) ServiceClient() *FileServiceClient { + return s.fsc +} + +// SetMetadata replaces the metadata for this share. +// +// Some keys may be converted to Camel-Case before sending. All keys +// are returned in lower case by GetShareMetadata. HTTP header names +// are case-insensitive so case munging should not matter to other +// applications either. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/set-share-metadata +func (s *Share) SetMetadata(options *FileRequestOptions) error { + headers, err := s.fsc.setResourceHeaders(s.buildPath(), compMetadata, resourceShare, mergeMDIntoExtraHeaders(s.Metadata, nil), options) + if err != nil { + return err + } + + s.updateEtagAndLastModified(headers) + return nil +} + +// SetProperties sets system properties for this share. +// +// Some keys may be converted to Camel-Case before sending. All keys +// are returned in lower case by SetShareProperties. HTTP header names +// are case-insensitive so case munging should not matter to other +// applications either. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Set-Share-Properties +func (s *Share) SetProperties(options *FileRequestOptions) error { + extraheaders := map[string]string{} + if s.Properties.Quota > 0 { + if s.Properties.Quota > 5120 { + return fmt.Errorf("invalid value %v for quota, valid values are [1, 5120]", s.Properties.Quota) + } + extraheaders["x-ms-share-quota"] = strconv.Itoa(s.Properties.Quota) + } + + headers, err := s.fsc.setResourceHeaders(s.buildPath(), compProperties, resourceShare, extraheaders, options) + if err != nil { + return err + } + + s.updateEtagAndLastModified(headers) + return nil +} + +// updates Etag and last modified date +func (s *Share) updateEtagAndLastModified(headers http.Header) { + s.Properties.Etag = headers.Get("Etag") + s.Properties.LastModified = headers.Get("Last-Modified") +} + +// updates quota value +func (s *Share) updateQuota(headers http.Header) { + quota, err := strconv.Atoi(headers.Get("x-ms-share-quota")) + if err == nil { + s.Properties.Quota = quota + } +} + +// URL gets the canonical URL to this share. This method does not create a publicly accessible +// URL if the share is private and this method does not check if the share exists. +func (s *Share) URL() string { + return s.fsc.client.getEndpoint(fileServiceName, s.buildPath(), url.Values{}) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/storagepolicy.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/storagepolicy.go new file mode 100644 index 000000000000..bee1c31ad61f --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/storagepolicy.go @@ -0,0 +1,47 @@ +package storage + +import ( + "strings" + "time" +) + +// AccessPolicyDetailsXML has specifics about an access policy +// annotated with XML details. +type AccessPolicyDetailsXML struct { + StartTime time.Time `xml:"Start"` + ExpiryTime time.Time `xml:"Expiry"` + Permission string `xml:"Permission"` +} + +// SignedIdentifier is a wrapper for a specific policy +type SignedIdentifier struct { + ID string `xml:"Id"` + AccessPolicy AccessPolicyDetailsXML `xml:"AccessPolicy"` +} + +// SignedIdentifiers part of the response from GetPermissions call. +type SignedIdentifiers struct { + SignedIdentifiers []SignedIdentifier `xml:"SignedIdentifier"` +} + +// AccessPolicy is the response type from the GetPermissions call. +type AccessPolicy struct { + SignedIdentifiersList SignedIdentifiers `xml:"SignedIdentifiers"` +} + +// convertAccessPolicyToXMLStructs converts between AccessPolicyDetails which is a struct better for API usage to the +// AccessPolicy struct which will get converted to XML. +func convertAccessPolicyToXMLStructs(id string, startTime time.Time, expiryTime time.Time, permissions string) SignedIdentifier { + return SignedIdentifier{ + ID: id, + AccessPolicy: AccessPolicyDetailsXML{ + StartTime: startTime.UTC().Round(time.Second), + ExpiryTime: expiryTime.UTC().Round(time.Second), + Permission: permissions, + }, + } +} + +func updatePermissions(permissions, permission string) bool { + return strings.Contains(permissions, permission) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/storageservice.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/storageservice.go new file mode 100644 index 000000000000..88700fbc93e6 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/storageservice.go @@ -0,0 +1,117 @@ +package storage + +import ( + "net/http" + "net/url" + "strconv" +) + +// ServiceProperties represents the storage account service properties +type ServiceProperties struct { + Logging *Logging + HourMetrics *Metrics + MinuteMetrics *Metrics + Cors *Cors +} + +// Logging represents the Azure Analytics Logging settings +type Logging struct { + Version string + Delete bool + Read bool + Write bool + RetentionPolicy *RetentionPolicy +} + +// RetentionPolicy indicates if retention is enabled and for how many days +type RetentionPolicy struct { + Enabled bool + Days *int +} + +// Metrics provide request statistics. +type Metrics struct { + Version string + Enabled bool + IncludeAPIs *bool + RetentionPolicy *RetentionPolicy +} + +// Cors includes all the CORS rules +type Cors struct { + CorsRule []CorsRule +} + +// CorsRule includes all settings for a Cors rule +type CorsRule struct { + AllowedOrigins string + AllowedMethods string + MaxAgeInSeconds int + ExposedHeaders string + AllowedHeaders string +} + +func (c Client) getServiceProperties(service string, auth authentication) (*ServiceProperties, error) { + query := url.Values{ + "restype": {"service"}, + "comp": {"properties"}, + } + uri := c.getEndpoint(service, "", query) + headers := c.getStandardHeaders() + + resp, err := c.exec(http.MethodGet, uri, headers, nil, auth) + if err != nil { + return nil, err + } + defer resp.body.Close() + + if err := checkRespCode(resp.statusCode, []int{http.StatusOK}); err != nil { + return nil, err + } + + var out ServiceProperties + err = xmlUnmarshal(resp.body, &out) + if err != nil { + return nil, err + } + + return &out, nil +} + +func (c Client) setServiceProperties(props ServiceProperties, service string, auth authentication) error { + query := url.Values{ + "restype": {"service"}, + "comp": {"properties"}, + } + uri := c.getEndpoint(service, "", query) + + // Ideally, StorageServiceProperties would be the output struct + // This is to avoid golint stuttering, while generating the correct XML + type StorageServiceProperties struct { + Logging *Logging + HourMetrics *Metrics + MinuteMetrics *Metrics + Cors *Cors + } + input := StorageServiceProperties{ + Logging: props.Logging, + HourMetrics: props.HourMetrics, + MinuteMetrics: props.MinuteMetrics, + Cors: props.Cors, + } + + body, length, err := xmlMarshal(input) + if err != nil { + return err + } + + headers := c.getStandardHeaders() + headers["Content-Length"] = strconv.Itoa(length) + + resp, err := c.exec(http.MethodPut, uri, headers, body, auth) + if err != nil { + return err + } + readAndCloseBody(resp.body) + return checkRespCode(resp.statusCode, []int{http.StatusAccepted}) +} 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 index 39e997503552..4eae3af9df76 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/storage/table.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/table.go @@ -4,126 +4,409 @@ import ( "bytes" "encoding/json" "fmt" + "io" + "io/ioutil" "net/http" "net/url" + "strconv" + "strings" + "time" ) -// TableServiceClient contains operations for Microsoft Azure Table Storage -// Service. -type TableServiceClient struct { - client Client +const ( + tablesURIPath = "/Tables" + nextTableQueryParameter = "NextTableName" + headerNextPartitionKey = "x-ms-continuation-NextPartitionKey" + headerNextRowKey = "x-ms-continuation-NextRowKey" + nextPartitionKeyQueryParameter = "NextPartitionKey" + nextRowKeyQueryParameter = "NextRowKey" +) + +// TableAccessPolicy are used for SETTING table policies +type TableAccessPolicy struct { + ID string + StartTime time.Time + ExpiryTime time.Time + CanRead bool + CanAppend bool + CanUpdate bool + CanDelete bool } -// AzureTable is the typedef of the Azure Table name -type AzureTable string +// Table represents an Azure table. +type Table struct { + tsc *TableServiceClient + Name string `json:"TableName"` + OdataEditLink string `json:"odata.editLink"` + OdataID string `json:"odata.id"` + OdataMetadata string `json:"odata.metadata"` + OdataType string `json:"odata.type"` +} -const ( - tablesURIPath = "/Tables" -) +// EntityQueryResult contains the response from +// ExecuteQuery and ExecuteQueryNextResults functions. +type EntityQueryResult struct { + OdataMetadata string `json:"odata.metadata"` + Entities []*Entity `json:"value"` + QueryNextLink + table *Table +} -type createTableRequest struct { - TableName string `json:"TableName"` +type continuationToken struct { + NextPartitionKey string + NextRowKey string } -func pathForTable(table AzureTable) string { return fmt.Sprintf("%s", table) } +func (t *Table) buildPath() string { + return fmt.Sprintf("/%s", t.Name) +} -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", - } +func (t *Table) buildSpecificPath() string { + return fmt.Sprintf("%s('%s')", tablesURIPath, t.Name) } -// QueryTables returns the tables created in the -// *TableServiceClient storage account. -func (c *TableServiceClient) QueryTables() ([]AzureTable, error) { - uri := c.client.getEndpoint(tableServiceName, tablesURIPath, url.Values{}) +// Get gets the referenced table. +// See: https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/querying-tables-and-entities +func (t *Table) Get(timeout uint, ml MetadataLevel) error { + if ml == EmptyPayload { + return errEmptyPayload + } - headers := c.getStandardHeaders() - headers["Content-Length"] = "0" + query := url.Values{ + "timeout": {strconv.FormatUint(uint64(timeout), 10)}, + } + headers := t.tsc.client.getStandardHeaders() + headers[headerAccept] = string(ml) - resp, err := c.client.execTable("GET", uri, headers, nil) + uri := t.tsc.client.getEndpoint(tableServiceName, t.buildSpecificPath(), query) + resp, err := t.tsc.client.exec(http.MethodGet, uri, headers, nil, t.tsc.auth) if err != nil { - return nil, err + return err } - defer resp.body.Close() + defer readAndCloseBody(resp.body) - if err := checkRespCode(resp.statusCode, []int{http.StatusOK}); err != nil { - return nil, err + if err = checkRespCode(resp.statusCode, []int{http.StatusOK}); err != nil { + return err } + respBody, err := ioutil.ReadAll(resp.body) + if err != nil { + return err + } + err = json.Unmarshal(respBody, t) + if err != nil { + return err + } + return nil +} + +// Create creates the referenced table. +// This function fails if the name is not compliant +// with the specification or the tables already exists. +// ml determines the level of detail of metadata in the operation response, +// or no data at all. +// See https://docs.microsoft.com/rest/api/storageservices/fileservices/create-table +func (t *Table) Create(timeout uint, ml MetadataLevel, options *TableOptions) error { + uri := t.tsc.client.getEndpoint(tableServiceName, tablesURIPath, url.Values{ + "timeout": {strconv.FormatUint(uint64(timeout), 10)}, + }) + + type createTableRequest struct { + TableName string `json:"TableName"` + } + req := createTableRequest{TableName: t.Name} buf := new(bytes.Buffer) - buf.ReadFrom(resp.body) + if err := json.NewEncoder(buf).Encode(req); err != nil { + return err + } - var respArray queryTablesResponse - if err := json.Unmarshal(buf.Bytes(), &respArray); err != nil { - return nil, err + headers := t.tsc.client.getStandardHeaders() + headers = addReturnContentHeaders(headers, ml) + headers = addBodyRelatedHeaders(headers, buf.Len()) + headers = options.addToHeaders(headers) + + resp, err := t.tsc.client.exec(http.MethodPost, uri, headers, buf, t.tsc.auth) + if err != nil { + return err + } + defer readAndCloseBody(resp.body) + + if ml == EmptyPayload { + if err := checkRespCode(resp.statusCode, []int{http.StatusNoContent}); err != nil { + return err + } + } else { + if err := checkRespCode(resp.statusCode, []int{http.StatusCreated}); err != nil { + return err + } } - s := make([]AzureTable, len(respArray.TableName)) - for i, elem := range respArray.TableName { - s[i] = AzureTable(elem.TableName) + if ml != EmptyPayload { + data, err := ioutil.ReadAll(resp.body) + if err != nil { + return err + } + err = json.Unmarshal(data, t) + if err != nil { + return err + } } - return s, nil + return 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{}) +// Delete deletes the referenced table. +// This function fails if the table is not present. +// Be advised: Delete deletes all the entries that may be present. +// See https://docs.microsoft.com/rest/api/storageservices/fileservices/delete-table +func (t *Table) Delete(timeout uint, options *TableOptions) error { + uri := t.tsc.client.getEndpoint(tableServiceName, t.buildSpecificPath(), url.Values{ + "timeout": {strconv.Itoa(int(timeout))}, + }) - headers := c.getStandardHeaders() + headers := t.tsc.client.getStandardHeaders() + headers = addReturnContentHeaders(headers, EmptyPayload) + headers = options.addToHeaders(headers) - req := createTableRequest{TableName: string(table)} - buf := new(bytes.Buffer) + resp, err := t.tsc.client.exec(http.MethodDelete, uri, headers, nil, t.tsc.auth) + if err != nil { + return err + } + defer readAndCloseBody(resp.body) - if err := json.NewEncoder(buf).Encode(req); err != nil { + if err := checkRespCode(resp.statusCode, []int{http.StatusNoContent}); err != nil { return err + } + return nil +} + +// QueryOptions includes options for a query entities operation. +// Top, filter and select are OData query options. +type QueryOptions struct { + Top uint + Filter string + Select []string + RequestID string +} - headers["Content-Length"] = fmt.Sprintf("%d", buf.Len()) +func (options *QueryOptions) getParameters() (url.Values, map[string]string) { + query := url.Values{} + headers := map[string]string{} + if options != nil { + if options.Top > 0 { + query.Add(OdataTop, strconv.FormatUint(uint64(options.Top), 10)) + } + if options.Filter != "" { + query.Add(OdataFilter, options.Filter) + } + if len(options.Select) > 0 { + query.Add(OdataSelect, strings.Join(options.Select, ",")) + } + headers = addToHeaders(headers, "x-ms-client-request-id", options.RequestID) + } + return query, headers +} - resp, err := c.client.execTable("POST", uri, headers, buf) +// QueryEntities returns the entities in the table. +// You can use query options defined by the OData Protocol specification. +// +// See: https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/query-entities +func (t *Table) QueryEntities(timeout uint, ml MetadataLevel, options *QueryOptions) (*EntityQueryResult, error) { + if ml == EmptyPayload { + return nil, errEmptyPayload + } + query, headers := options.getParameters() + query = addTimeout(query, timeout) + uri := t.tsc.client.getEndpoint(tableServiceName, t.buildPath(), query) + return t.queryEntities(uri, headers, ml) +} + +// NextResults returns the next page of results +// from a QueryEntities or NextResults operation. +// +// See: https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/query-entities +// See https://docs.microsoft.com/rest/api/storageservices/fileservices/query-timeout-and-pagination +func (eqr *EntityQueryResult) NextResults(options *TableOptions) (*EntityQueryResult, error) { + if eqr == nil { + return nil, errNilPreviousResult + } + if eqr.NextLink == nil { + return nil, errNilNextLink + } + headers := options.addToHeaders(map[string]string{}) + return eqr.table.queryEntities(*eqr.NextLink, headers, eqr.ml) +} + +// SetPermissions sets up table ACL permissions +// See https://docs.microsoft.com/rest/api/storageservices/fileservices/Set-Table-ACL +func (t *Table) SetPermissions(tap []TableAccessPolicy, timeout uint, options *TableOptions) error { + params := url.Values{"comp": {"acl"}, + "timeout": {strconv.Itoa(int(timeout))}, + } + uri := t.tsc.client.getEndpoint(tableServiceName, t.Name, params) + headers := t.tsc.client.getStandardHeaders() + headers = options.addToHeaders(headers) + + body, length, err := generateTableACLPayload(tap) if err != nil { return err } - defer resp.body.Close() + headers["Content-Length"] = strconv.Itoa(length) - if err := checkRespCode(resp.statusCode, []int{http.StatusCreated}); err != nil { + resp, err := t.tsc.client.exec(http.MethodPut, uri, headers, body, t.tsc.auth) + if err != nil { return err } + defer readAndCloseBody(resp.body) + if err := checkRespCode(resp.statusCode, []int{http.StatusNoContent}); 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)) +func generateTableACLPayload(policies []TableAccessPolicy) (io.Reader, int, error) { + sil := SignedIdentifiers{ + SignedIdentifiers: []SignedIdentifier{}, + } + for _, tap := range policies { + permission := generateTablePermissions(&tap) + signedIdentifier := convertAccessPolicyToXMLStructs(tap.ID, tap.StartTime, tap.ExpiryTime, permission) + sil.SignedIdentifiers = append(sil.SignedIdentifiers, signedIdentifier) + } + return xmlMarshal(sil) +} + +// GetPermissions gets the table ACL permissions +// See https://docs.microsoft.com/rest/api/storageservices/fileservices/get-table-acl +func (t *Table) GetPermissions(timeout int, options *TableOptions) ([]TableAccessPolicy, error) { + params := url.Values{"comp": {"acl"}, + "timeout": {strconv.Itoa(int(timeout))}, + } + + uri := t.tsc.client.getEndpoint(tableServiceName, t.Name, params) + headers := t.tsc.client.getStandardHeaders() + headers = options.addToHeaders(headers) + + resp, err := t.tsc.client.exec(http.MethodGet, uri, headers, nil, t.tsc.auth) + if err != nil { + return nil, err + } + defer resp.body.Close() - headers := c.getStandardHeaders() + if err = checkRespCode(resp.statusCode, []int{http.StatusOK}); err != nil { + return nil, err + } - headers["Content-Length"] = "0" + var ap AccessPolicy + err = xmlUnmarshal(resp.body, &ap.SignedIdentifiersList) + if err != nil { + return nil, err + } + return updateTableAccessPolicy(ap), nil +} - resp, err := c.client.execTable("DELETE", uri, headers, nil) +func (t *Table) queryEntities(uri string, headers map[string]string, ml MetadataLevel) (*EntityQueryResult, error) { + headers = mergeHeaders(headers, t.tsc.client.getStandardHeaders()) + if ml != EmptyPayload { + headers[headerAccept] = string(ml) + } + resp, err := t.tsc.client.exec(http.MethodGet, uri, headers, nil, t.tsc.auth) if err != nil { - return err + return nil, err } defer resp.body.Close() - if err := checkRespCode(resp.statusCode, []int{http.StatusNoContent}); err != nil { - return err + if err = checkRespCode(resp.statusCode, []int{http.StatusOK}); err != nil { + return nil, err + } + data, err := ioutil.ReadAll(resp.body) + if err != nil { + return nil, err + } + var entities EntityQueryResult + err = json.Unmarshal(data, &entities) + if err != nil { + return nil, err + } + + for i := range entities.Entities { + entities.Entities[i].Table = t + } + entities.table = t + + contToken := extractContinuationTokenFromHeaders(resp.headers) + if contToken == nil { + entities.NextLink = nil + } else { + originalURI, err := url.Parse(uri) + if err != nil { + return nil, err + } + v := originalURI.Query() + v.Set(nextPartitionKeyQueryParameter, contToken.NextPartitionKey) + v.Set(nextRowKeyQueryParameter, contToken.NextRowKey) + newURI := t.tsc.client.getEndpoint(tableServiceName, t.buildPath(), v) + entities.NextLink = &newURI + entities.ml = ml + } + + return &entities, nil +} + +func extractContinuationTokenFromHeaders(h http.Header) *continuationToken { + ct := continuationToken{ + NextPartitionKey: h.Get(headerNextPartitionKey), + NextRowKey: h.Get(headerNextRowKey), + } + + if ct.NextPartitionKey != "" && ct.NextRowKey != "" { + return &ct } return nil } + +func updateTableAccessPolicy(ap AccessPolicy) []TableAccessPolicy { + taps := []TableAccessPolicy{} + for _, policy := range ap.SignedIdentifiersList.SignedIdentifiers { + tap := TableAccessPolicy{ + ID: policy.ID, + StartTime: policy.AccessPolicy.StartTime, + ExpiryTime: policy.AccessPolicy.ExpiryTime, + } + tap.CanRead = updatePermissions(policy.AccessPolicy.Permission, "r") + tap.CanAppend = updatePermissions(policy.AccessPolicy.Permission, "a") + tap.CanUpdate = updatePermissions(policy.AccessPolicy.Permission, "u") + tap.CanDelete = updatePermissions(policy.AccessPolicy.Permission, "d") + + taps = append(taps, tap) + } + return taps +} + +func generateTablePermissions(tap *TableAccessPolicy) (permissions string) { + // generate the permissions string (raud). + // still want the end user API to have bool flags. + permissions = "" + + if tap.CanRead { + permissions += "r" + } + + if tap.CanAppend { + permissions += "a" + } + + if tap.CanUpdate { + permissions += "u" + } + + if tap.CanDelete { + permissions += "d" + } + return permissions +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/table_batch.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/table_batch.go new file mode 100644 index 000000000000..7a0f0915c627 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/table_batch.go @@ -0,0 +1,302 @@ +package storage + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "mime/multipart" + "net/http" + "net/textproto" + "sort" + "strings" + + "github.com/satori/uuid" +) + +// Operation type. Insert, Delete, Replace etc. +type Operation int + +// consts for batch operations. +const ( + InsertOp = Operation(1) + DeleteOp = Operation(2) + ReplaceOp = Operation(3) + MergeOp = Operation(4) + InsertOrReplaceOp = Operation(5) + InsertOrMergeOp = Operation(6) +) + +// BatchEntity used for tracking Entities to operate on and +// whether operations (replace/merge etc) should be forced. +// Wrapper for regular Entity with additional data specific for the entity. +type BatchEntity struct { + *Entity + Force bool + Op Operation +} + +// TableBatch stores all the entities that will be operated on during a batch process. +// Entities can be inserted, replaced or deleted. +type TableBatch struct { + BatchEntitySlice []BatchEntity + + // reference to table we're operating on. + Table *Table +} + +// defaultChangesetHeaders for changeSets +var defaultChangesetHeaders = map[string]string{ + "Accept": "application/json;odata=minimalmetadata", + "Content-Type": "application/json", + "Prefer": "return-no-content", +} + +// NewBatch return new TableBatch for populating. +func (t *Table) NewBatch() *TableBatch { + return &TableBatch{ + Table: t, + } +} + +// InsertEntity adds an entity in preparation for a batch insert. +func (t *TableBatch) InsertEntity(entity *Entity) { + be := BatchEntity{Entity: entity, Force: false, Op: InsertOp} + t.BatchEntitySlice = append(t.BatchEntitySlice, be) +} + +// InsertOrReplaceEntity adds an entity in preparation for a batch insert or replace. +func (t *TableBatch) InsertOrReplaceEntity(entity *Entity, force bool) { + be := BatchEntity{Entity: entity, Force: false, Op: InsertOrReplaceOp} + t.BatchEntitySlice = append(t.BatchEntitySlice, be) +} + +// InsertOrReplaceEntityByForce adds an entity in preparation for a batch insert or replace. Forces regardless of ETag +func (t *TableBatch) InsertOrReplaceEntityByForce(entity *Entity) { + t.InsertOrReplaceEntity(entity, true) +} + +// InsertOrMergeEntity adds an entity in preparation for a batch insert or merge. +func (t *TableBatch) InsertOrMergeEntity(entity *Entity, force bool) { + be := BatchEntity{Entity: entity, Force: false, Op: InsertOrMergeOp} + t.BatchEntitySlice = append(t.BatchEntitySlice, be) +} + +// InsertOrMergeEntityByForce adds an entity in preparation for a batch insert or merge. Forces regardless of ETag +func (t *TableBatch) InsertOrMergeEntityByForce(entity *Entity) { + t.InsertOrMergeEntity(entity, true) +} + +// ReplaceEntity adds an entity in preparation for a batch replace. +func (t *TableBatch) ReplaceEntity(entity *Entity) { + be := BatchEntity{Entity: entity, Force: false, Op: ReplaceOp} + t.BatchEntitySlice = append(t.BatchEntitySlice, be) +} + +// DeleteEntity adds an entity in preparation for a batch delete +func (t *TableBatch) DeleteEntity(entity *Entity, force bool) { + be := BatchEntity{Entity: entity, Force: false, Op: DeleteOp} + t.BatchEntitySlice = append(t.BatchEntitySlice, be) +} + +// DeleteEntityByForce adds an entity in preparation for a batch delete. Forces regardless of ETag +func (t *TableBatch) DeleteEntityByForce(entity *Entity, force bool) { + t.DeleteEntity(entity, true) +} + +// MergeEntity adds an entity in preparation for a batch merge +func (t *TableBatch) MergeEntity(entity *Entity) { + be := BatchEntity{Entity: entity, Force: false, Op: MergeOp} + t.BatchEntitySlice = append(t.BatchEntitySlice, be) +} + +// ExecuteBatch executes many table operations in one request to Azure. +// The operations can be combinations of Insert, Delete, Replace and Merge +// Creates the inner changeset body (various operations, Insert, Delete etc) then creates the outer request packet that encompasses +// the changesets. +// As per document https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/performing-entity-group-transactions +func (t *TableBatch) ExecuteBatch() error { + changesetBoundary := fmt.Sprintf("changeset_%s", uuid.NewV1()) + uri := t.Table.tsc.client.getEndpoint(tableServiceName, "$batch", nil) + changesetBody, err := t.generateChangesetBody(changesetBoundary) + if err != nil { + return err + } + + boundary := fmt.Sprintf("batch_%s", uuid.NewV1()) + body, err := generateBody(changesetBody, changesetBoundary, boundary) + if err != nil { + return err + } + + headers := t.Table.tsc.client.getStandardHeaders() + headers[headerContentType] = fmt.Sprintf("multipart/mixed; boundary=%s", boundary) + + resp, err := t.Table.tsc.client.execBatchOperationJSON(http.MethodPost, uri, headers, bytes.NewReader(body.Bytes()), t.Table.tsc.auth) + if err != nil { + return err + } + defer resp.body.Close() + + if err = checkRespCode(resp.statusCode, []int{http.StatusAccepted}); err != nil { + + // check which batch failed. + operationFailedMessage := t.getFailedOperation(resp.odata.Err.Message.Value) + requestID, date, version := getDebugHeaders(resp.headers) + return AzureStorageServiceError{ + StatusCode: resp.statusCode, + Code: resp.odata.Err.Code, + RequestID: requestID, + Date: date, + APIVersion: version, + Message: operationFailedMessage, + } + } + + return nil +} + +// getFailedOperation parses the original Azure error string and determines which operation failed +// and generates appropriate message. +func (t *TableBatch) getFailedOperation(errorMessage string) string { + // errorMessage consists of "number:string" we just need the number. + sp := strings.Split(errorMessage, ":") + if len(sp) > 1 { + msg := fmt.Sprintf("Element %s in the batch returned an unexpected response code.\n%s", sp[0], errorMessage) + return msg + } + + // cant parse the message, just return the original message to client + return errorMessage +} + +// generateBody generates the complete body for the batch request. +func generateBody(changeSetBody *bytes.Buffer, changesetBoundary string, boundary string) (*bytes.Buffer, error) { + + body := new(bytes.Buffer) + writer := multipart.NewWriter(body) + writer.SetBoundary(boundary) + h := make(textproto.MIMEHeader) + h.Set(headerContentType, fmt.Sprintf("multipart/mixed; boundary=%s\r\n", changesetBoundary)) + batchWriter, err := writer.CreatePart(h) + if err != nil { + return nil, err + } + batchWriter.Write(changeSetBody.Bytes()) + writer.Close() + return body, nil +} + +// generateChangesetBody generates the individual changesets for the various operations within the batch request. +// There is a changeset for Insert, Delete, Merge etc. +func (t *TableBatch) generateChangesetBody(changesetBoundary string) (*bytes.Buffer, error) { + + body := new(bytes.Buffer) + writer := multipart.NewWriter(body) + writer.SetBoundary(changesetBoundary) + + for _, be := range t.BatchEntitySlice { + t.generateEntitySubset(&be, writer) + } + + writer.Close() + return body, nil +} + +// generateVerb generates the HTTP request VERB required for each changeset. +func generateVerb(op Operation) (string, error) { + switch op { + case InsertOp: + return http.MethodPost, nil + case DeleteOp: + return http.MethodDelete, nil + case ReplaceOp, InsertOrReplaceOp: + return http.MethodPut, nil + case MergeOp, InsertOrMergeOp: + return "MERGE", nil + default: + return "", errors.New("Unable to detect operation") + } +} + +// generateQueryPath generates the query path for within the changesets +// For inserts it will just be a table query path (table name) +// but for other operations (modifying an existing entity) then +// the partition/row keys need to be generated. +func (t *TableBatch) generateQueryPath(op Operation, entity *Entity) string { + if op == InsertOp { + return entity.Table.buildPath() + } + return entity.buildPath() +} + +// generateGenericOperationHeaders generates common headers for a given operation. +func generateGenericOperationHeaders(be *BatchEntity) map[string]string { + retval := map[string]string{} + + for k, v := range defaultChangesetHeaders { + retval[k] = v + } + + if be.Op == DeleteOp || be.Op == ReplaceOp || be.Op == MergeOp { + if be.Force || be.Entity.OdataEtag == "" { + retval["If-Match"] = "*" + } else { + retval["If-Match"] = be.Entity.OdataEtag + } + } + + return retval +} + +// generateEntitySubset generates body payload for particular batch entity +func (t *TableBatch) generateEntitySubset(batchEntity *BatchEntity, writer *multipart.Writer) error { + + h := make(textproto.MIMEHeader) + h.Set(headerContentType, "application/http") + h.Set(headerContentTransferEncoding, "binary") + + verb, err := generateVerb(batchEntity.Op) + if err != nil { + return err + } + + genericOpHeadersMap := generateGenericOperationHeaders(batchEntity) + queryPath := t.generateQueryPath(batchEntity.Op, batchEntity.Entity) + uri := t.Table.tsc.client.getEndpoint(tableServiceName, queryPath, nil) + + operationWriter, err := writer.CreatePart(h) + if err != nil { + return err + } + + urlAndVerb := fmt.Sprintf("%s %s HTTP/1.1\r\n", verb, uri) + operationWriter.Write([]byte(urlAndVerb)) + writeHeaders(genericOpHeadersMap, &operationWriter) + operationWriter.Write([]byte("\r\n")) // additional \r\n is needed per changeset separating the "headers" and the body. + + // delete operation doesn't need a body. + if batchEntity.Op != DeleteOp { + //var e Entity = batchEntity.Entity + body, err := json.Marshal(batchEntity.Entity) + if err != nil { + return err + } + operationWriter.Write(body) + } + + return nil +} + +func writeHeaders(h map[string]string, writer *io.Writer) { + // This way it is guaranteed the headers will be written in a sorted order + var keys []string + for k := range h { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + (*writer).Write([]byte(fmt.Sprintf("%s: %s\r\n", k, h[k]))) + } +} 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 deleted file mode 100644 index a26d9c6f581f..000000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/storage/table_entities.go +++ /dev/null @@ -1,357 +0,0 @@ -package storage - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "reflect" -) - -// Annotating as secure for gas scanning -/* #nosec */ -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) - - if err != nil { - return nil, nil, err - } - - 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/azure-sdk-for-go/storage/tableserviceclient.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/tableserviceclient.go new file mode 100644 index 000000000000..895dcfded891 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/tableserviceclient.go @@ -0,0 +1,190 @@ +package storage + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "net/url" + "strconv" +) + +const ( + headerAccept = "Accept" + headerEtag = "Etag" + headerPrefer = "Prefer" + headerXmsContinuation = "x-ms-Continuation-NextTableName" +) + +// TableServiceClient contains operations for Microsoft Azure Table Storage +// Service. +type TableServiceClient struct { + client Client + auth authentication +} + +// TableOptions includes options for some table operations +type TableOptions struct { + RequestID string +} + +func (options *TableOptions) addToHeaders(h map[string]string) map[string]string { + if options != nil { + h = addToHeaders(h, "x-ms-client-request-id", options.RequestID) + } + return h +} + +// QueryNextLink includes information for getting the next page of +// results in query operations +type QueryNextLink struct { + NextLink *string + ml MetadataLevel +} + +// GetServiceProperties gets the properties of your storage account's table service. +// See: https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/get-table-service-properties +func (t *TableServiceClient) GetServiceProperties() (*ServiceProperties, error) { + return t.client.getServiceProperties(tableServiceName, t.auth) +} + +// SetServiceProperties sets the properties of your storage account's table service. +// See: https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/set-table-service-properties +func (t *TableServiceClient) SetServiceProperties(props ServiceProperties) error { + return t.client.setServiceProperties(props, tableServiceName, t.auth) +} + +// GetTableReference returns a Table object for the specified table name. +func (t *TableServiceClient) GetTableReference(name string) *Table { + return &Table{ + tsc: t, + Name: name, + } +} + +// QueryTablesOptions includes options for some table operations +type QueryTablesOptions struct { + Top uint + Filter string + RequestID string +} + +func (options *QueryTablesOptions) getParameters() (url.Values, map[string]string) { + query := url.Values{} + headers := map[string]string{} + if options != nil { + if options.Top > 0 { + query.Add(OdataTop, strconv.FormatUint(uint64(options.Top), 10)) + } + if options.Filter != "" { + query.Add(OdataFilter, options.Filter) + } + headers = addToHeaders(headers, "x-ms-client-request-id", options.RequestID) + } + return query, headers +} + +// QueryTables returns the tables in the storage account. +// You can use query options defined by the OData Protocol specification. +// +// See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/query-tables +func (t *TableServiceClient) QueryTables(ml MetadataLevel, options *QueryTablesOptions) (*TableQueryResult, error) { + query, headers := options.getParameters() + uri := t.client.getEndpoint(tableServiceName, tablesURIPath, query) + return t.queryTables(uri, headers, ml) +} + +// NextResults returns the next page of results +// from a QueryTables or a NextResults operation. +// +// See https://docs.microsoft.com/rest/api/storageservices/fileservices/query-tables +// See https://docs.microsoft.com/rest/api/storageservices/fileservices/query-timeout-and-pagination +func (tqr *TableQueryResult) NextResults(options *TableOptions) (*TableQueryResult, error) { + if tqr == nil { + return nil, errNilPreviousResult + } + if tqr.NextLink == nil { + return nil, errNilNextLink + } + headers := options.addToHeaders(map[string]string{}) + + return tqr.tsc.queryTables(*tqr.NextLink, headers, tqr.ml) +} + +// TableQueryResult contains the response from +// QueryTables and QueryTablesNextResults functions. +type TableQueryResult struct { + OdataMetadata string `json:"odata.metadata"` + Tables []Table `json:"value"` + QueryNextLink + tsc *TableServiceClient +} + +func (t *TableServiceClient) queryTables(uri string, headers map[string]string, ml MetadataLevel) (*TableQueryResult, error) { + if ml == EmptyPayload { + return nil, errEmptyPayload + } + headers = mergeHeaders(headers, t.client.getStandardHeaders()) + headers[headerAccept] = string(ml) + + resp, err := t.client.exec(http.MethodGet, uri, headers, nil, t.auth) + if err != nil { + return nil, err + } + defer resp.body.Close() + + if err := checkRespCode(resp.statusCode, []int{http.StatusOK}); err != nil { + return nil, err + } + + respBody, err := ioutil.ReadAll(resp.body) + if err != nil { + return nil, err + } + var out TableQueryResult + err = json.Unmarshal(respBody, &out) + if err != nil { + return nil, err + } + + for i := range out.Tables { + out.Tables[i].tsc = t + } + out.tsc = t + + nextLink := resp.headers.Get(http.CanonicalHeaderKey(headerXmsContinuation)) + if nextLink == "" { + out.NextLink = nil + } else { + originalURI, err := url.Parse(uri) + if err != nil { + return nil, err + } + v := originalURI.Query() + v.Set(nextTableQueryParameter, nextLink) + newURI := t.client.getEndpoint(tableServiceName, tablesURIPath, v) + out.NextLink = &newURI + out.ml = ml + } + + return &out, nil +} + +func addBodyRelatedHeaders(h map[string]string, length int) map[string]string { + h[headerContentType] = "application/json" + h[headerContentLength] = fmt.Sprintf("%v", length) + h[headerAcceptCharset] = "UTF-8" + return h +} + +func addReturnContentHeaders(h map[string]string, ml MetadataLevel) map[string]string { + if ml != EmptyPayload { + h[headerPrefer] = "return-content" + h[headerAccept] = string(ml) + } else { + h[headerPrefer] = "return-no-content" + // From API version 2015-12-11 onwards, Accept header is required + h[headerAccept] = string(NoMetadata) + } + return h +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/util.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/util.go index 57ca1b6d937e..8a902be2f05b 100644 --- a/vendor/github.com/Azure/azure-sdk-for-go/storage/util.go +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/util.go @@ -12,9 +12,15 @@ import ( "net/http" "net/url" "reflect" + "strconv" + "strings" "time" ) +var ( + fixedTime = time.Date(2050, time.December, 20, 21, 55, 0, 0, time.FixedZone("GMT", -6)) +) + func (c Client) computeHmac256(message string) string { h := hmac.New(sha256.New, c.accountKey) h.Write([]byte(message)) @@ -76,10 +82,118 @@ func headersFromStruct(v interface{}) map[string]string { value := reflect.ValueOf(v) for i := 0; i < value.NumField(); i++ { key := value.Type().Field(i).Tag.Get("header") - val := value.Field(i).String() - if key != "" && val != "" { - headers[key] = val + if key != "" { + reflectedValue := reflect.Indirect(value.Field(i)) + var val string + if reflectedValue.IsValid() { + switch reflectedValue.Type() { + case reflect.TypeOf(fixedTime): + val = timeRfc1123Formatted(reflectedValue.Interface().(time.Time)) + case reflect.TypeOf(uint64(0)), reflect.TypeOf(uint(0)): + val = strconv.FormatUint(reflectedValue.Uint(), 10) + case reflect.TypeOf(int(0)): + val = strconv.FormatInt(reflectedValue.Int(), 10) + default: + val = reflectedValue.String() + } + } + if val != "" { + headers[key] = val + } } } return headers } + +// merges extraHeaders into headers and returns headers +func mergeHeaders(headers, extraHeaders map[string]string) map[string]string { + for k, v := range extraHeaders { + headers[k] = v + } + return headers +} + +func addToHeaders(h map[string]string, key, value string) map[string]string { + if value != "" { + h[key] = value + } + return h +} + +func addTimeToHeaders(h map[string]string, key string, value *time.Time) map[string]string { + if value != nil { + h = addToHeaders(h, key, timeRfc1123Formatted(*value)) + } + return h +} + +func addTimeout(params url.Values, timeout uint) url.Values { + if timeout > 0 { + params.Add("timeout", fmt.Sprintf("%v", timeout)) + } + return params +} + +func addSnapshot(params url.Values, snapshot *time.Time) url.Values { + if snapshot != nil { + params.Add("snapshot", timeRfc1123Formatted(*snapshot)) + } + return params +} + +func getTimeFromHeaders(h http.Header, key string) (*time.Time, error) { + var out time.Time + var err error + outStr := h.Get(key) + if outStr != "" { + out, err = time.Parse(time.RFC1123, outStr) + if err != nil { + return nil, err + } + } + return &out, nil +} + +// TimeRFC1123 is an alias for time.Time needed for custom Unmarshalling +type TimeRFC1123 time.Time + +// UnmarshalXML is a custom unmarshaller that overrides the default time unmarshal which uses a different time layout. +func (t *TimeRFC1123) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { + var value string + d.DecodeElement(&value, &start) + parse, err := time.Parse(time.RFC1123, value) + if err != nil { + return err + } + *t = TimeRFC1123(parse) + return nil +} + +// returns a map of custom metadata values from the specified HTTP header +func getMetadataFromHeaders(header http.Header) map[string]string { + metadata := make(map[string]string) + for k, v := range header { + // Can't trust CanonicalHeaderKey() to munge case + // reliably. "_" is allowed in identifiers: + // https://msdn.microsoft.com/en-us/library/azure/dd179414.aspx + // https://msdn.microsoft.com/library/aa664670(VS.71).aspx + // http://tools.ietf.org/html/rfc7230#section-3.2 + // ...but "_" is considered invalid by + // CanonicalMIMEHeaderKey in + // https://golang.org/src/net/textproto/reader.go?s=14615:14659#L542 + // so k can be "X-Ms-Meta-Lol" or "x-ms-meta-lol_rofl". + k = strings.ToLower(k) + if len(v) == 0 || !strings.HasPrefix(k, strings.ToLower(userDefinedMetadataHeaderPrefix)) { + continue + } + // metadata["lol"] = content of the last X-Ms-Meta-Lol header + k = k[len(userDefinedMetadataHeaderPrefix):] + metadata[k] = v[len(v)-1] + } + + if len(metadata) == 0 { + return nil + } + + return metadata +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/storage/version.go b/vendor/github.com/Azure/azure-sdk-for-go/storage/version.go new file mode 100644 index 000000000000..a23fff1e2e15 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/storage/version.go @@ -0,0 +1,5 @@ +package storage + +var ( + sdkVersion = "10.0.2" +) diff --git a/vendor/github.com/Azure/go-ansiterm/BUILD b/vendor/github.com/Azure/go-ansiterm/BUILD index edc2de55fd06..6da8d8fba4e6 100644 --- a/vendor/github.com/Azure/go-ansiterm/BUILD +++ b/vendor/github.com/Azure/go-ansiterm/BUILD @@ -22,10 +22,7 @@ go_library( "parser.go", "parser_action_helpers.go", "parser_actions.go", - "parser_test_helpers.go", - "parser_test_utilities.go", "states.go", - "test_event_handler.go", "utilities.go", ], tags = ["automanaged"], diff --git a/vendor/github.com/Azure/go-ansiterm/README.md b/vendor/github.com/Azure/go-ansiterm/README.md index e25e38210168..261c041e7aba 100644 --- a/vendor/github.com/Azure/go-ansiterm/README.md +++ b/vendor/github.com/Azure/go-ansiterm/README.md @@ -7,3 +7,6 @@ For example the parser might receive "ESC, [, A" as a stream of three characters The parser (parser.go) is a partial implementation of this state machine (http://vt100.net/emu/vt500_parser.png). There are also two event handler implementations, one for tests (test_event_handler.go) to validate that the expected events are being produced and called, the other is a Windows implementation (winterm/win_event_handler.go). See parser_test.go for examples exercising the state machine and generating appropriate function calls. + +----- +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. diff --git a/vendor/github.com/Azure/go-ansiterm/constants.go b/vendor/github.com/Azure/go-ansiterm/constants.go index ebfce8a8d38b..96504a33bc9e 100644 --- a/vendor/github.com/Azure/go-ansiterm/constants.go +++ b/vendor/github.com/Azure/go-ansiterm/constants.go @@ -124,32 +124,32 @@ func getByteRange(start byte, end byte) []byte { return bytes } -var ToGroundBytes = getToGroundBytes() -var Executors = getExecuteBytes() +var toGroundBytes = getToGroundBytes() +var executors = getExecuteBytes() // SPACE 20+A0 hex Always and everywhere a blank space // Intermediate 20-2F hex !"#$%&'()*+,-./ -var Intermeds = getByteRange(0x20, 0x2F) +var intermeds = getByteRange(0x20, 0x2F) // Parameters 30-3F hex 0123456789:;<=>? // CSI Parameters 30-39, 3B hex 0123456789; -var CsiParams = getByteRange(0x30, 0x3F) +var csiParams = getByteRange(0x30, 0x3F) -var CsiCollectables = append(getByteRange(0x30, 0x39), getByteRange(0x3B, 0x3F)...) +var csiCollectables = append(getByteRange(0x30, 0x39), getByteRange(0x3B, 0x3F)...) // Uppercase 40-5F hex @ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_ -var UpperCase = getByteRange(0x40, 0x5F) +var upperCase = getByteRange(0x40, 0x5F) // Lowercase 60-7E hex `abcdefghijlkmnopqrstuvwxyz{|}~ -var LowerCase = getByteRange(0x60, 0x7E) +var lowerCase = getByteRange(0x60, 0x7E) // Alphabetics 40-7E hex (all of upper and lower case) -var Alphabetics = append(UpperCase, LowerCase...) +var alphabetics = append(upperCase, lowerCase...) -var Printables = getByteRange(0x20, 0x7F) +var printables = getByteRange(0x20, 0x7F) -var EscapeIntermediateToGroundBytes = getByteRange(0x30, 0x7E) -var EscapeToGroundBytes = getEscapeToGroundBytes() +var escapeIntermediateToGroundBytes = getByteRange(0x30, 0x7E) +var escapeToGroundBytes = getEscapeToGroundBytes() // See http://www.vt100.net/emu/vt500_parser.png for description of the complex // byte ranges below diff --git a/vendor/github.com/Azure/go-ansiterm/context.go b/vendor/github.com/Azure/go-ansiterm/context.go index d55cc2aec793..8d66e777c038 100644 --- a/vendor/github.com/Azure/go-ansiterm/context.go +++ b/vendor/github.com/Azure/go-ansiterm/context.go @@ -1,6 +1,6 @@ package ansiterm -type AnsiContext struct { +type ansiContext struct { currentChar byte paramBuffer []byte interBuffer []byte diff --git a/vendor/github.com/Azure/go-ansiterm/csi_entry_state.go b/vendor/github.com/Azure/go-ansiterm/csi_entry_state.go index 9fd4bd28e23f..1bd6057da8a8 100644 --- a/vendor/github.com/Azure/go-ansiterm/csi_entry_state.go +++ b/vendor/github.com/Azure/go-ansiterm/csi_entry_state.go @@ -1,41 +1,41 @@ package ansiterm -type CsiEntryState struct { - BaseState +type csiEntryState struct { + baseState } -func (csiState CsiEntryState) Handle(b byte) (s State, e error) { +func (csiState csiEntryState) Handle(b byte) (s state, e error) { logger.Infof("CsiEntry::Handle %#x", b) - nextState, err := csiState.BaseState.Handle(b) + nextState, err := csiState.baseState.Handle(b) if nextState != nil || err != nil { return nextState, err } switch { - case sliceContains(Alphabetics, b): - return csiState.parser.Ground, nil - case sliceContains(CsiCollectables, b): - return csiState.parser.CsiParam, nil - case sliceContains(Executors, b): + case sliceContains(alphabetics, b): + return csiState.parser.ground, nil + case sliceContains(csiCollectables, b): + return csiState.parser.csiParam, nil + case sliceContains(executors, b): return csiState, csiState.parser.execute() } return csiState, nil } -func (csiState CsiEntryState) Transition(s State) error { +func (csiState csiEntryState) Transition(s state) error { logger.Infof("CsiEntry::Transition %s --> %s", csiState.Name(), s.Name()) - csiState.BaseState.Transition(s) + csiState.baseState.Transition(s) switch s { - case csiState.parser.Ground: + case csiState.parser.ground: return csiState.parser.csiDispatch() - case csiState.parser.CsiParam: + case csiState.parser.csiParam: switch { - case sliceContains(CsiParams, csiState.parser.context.currentChar): + case sliceContains(csiParams, csiState.parser.context.currentChar): csiState.parser.collectParam() - case sliceContains(Intermeds, csiState.parser.context.currentChar): + case sliceContains(intermeds, csiState.parser.context.currentChar): csiState.parser.collectInter() } } @@ -43,7 +43,7 @@ func (csiState CsiEntryState) Transition(s State) error { return nil } -func (csiState CsiEntryState) Enter() error { +func (csiState csiEntryState) Enter() error { csiState.parser.clear() return nil } diff --git a/vendor/github.com/Azure/go-ansiterm/csi_param_state.go b/vendor/github.com/Azure/go-ansiterm/csi_param_state.go index 27807dd35b99..4be35c5fd2af 100644 --- a/vendor/github.com/Azure/go-ansiterm/csi_param_state.go +++ b/vendor/github.com/Azure/go-ansiterm/csi_param_state.go @@ -1,36 +1,36 @@ package ansiterm -type CsiParamState struct { - BaseState +type csiParamState struct { + baseState } -func (csiState CsiParamState) Handle(b byte) (s State, e error) { +func (csiState csiParamState) Handle(b byte) (s state, e error) { logger.Infof("CsiParam::Handle %#x", b) - nextState, err := csiState.BaseState.Handle(b) + nextState, err := csiState.baseState.Handle(b) if nextState != nil || err != nil { return nextState, err } switch { - case sliceContains(Alphabetics, b): - return csiState.parser.Ground, nil - case sliceContains(CsiCollectables, b): + case sliceContains(alphabetics, b): + return csiState.parser.ground, nil + case sliceContains(csiCollectables, b): csiState.parser.collectParam() return csiState, nil - case sliceContains(Executors, b): + case sliceContains(executors, b): return csiState, csiState.parser.execute() } return csiState, nil } -func (csiState CsiParamState) Transition(s State) error { +func (csiState csiParamState) Transition(s state) error { logger.Infof("CsiParam::Transition %s --> %s", csiState.Name(), s.Name()) - csiState.BaseState.Transition(s) + csiState.baseState.Transition(s) switch s { - case csiState.parser.Ground: + case csiState.parser.ground: return csiState.parser.csiDispatch() } diff --git a/vendor/github.com/Azure/go-ansiterm/escape_intermediate_state.go b/vendor/github.com/Azure/go-ansiterm/escape_intermediate_state.go index b14e0ce97736..2189eb6b6b06 100644 --- a/vendor/github.com/Azure/go-ansiterm/escape_intermediate_state.go +++ b/vendor/github.com/Azure/go-ansiterm/escape_intermediate_state.go @@ -1,34 +1,34 @@ package ansiterm -type EscapeIntermediateState struct { - BaseState +type escapeIntermediateState struct { + baseState } -func (escState EscapeIntermediateState) Handle(b byte) (s State, e error) { - logger.Infof("EscapeIntermediateState::Handle %#x", b) - nextState, err := escState.BaseState.Handle(b) +func (escState escapeIntermediateState) Handle(b byte) (s state, e error) { + logger.Infof("escapeIntermediateState::Handle %#x", b) + nextState, err := escState.baseState.Handle(b) if nextState != nil || err != nil { return nextState, err } switch { - case sliceContains(Intermeds, b): + case sliceContains(intermeds, b): return escState, escState.parser.collectInter() - case sliceContains(Executors, b): + case sliceContains(executors, b): return escState, escState.parser.execute() - case sliceContains(EscapeIntermediateToGroundBytes, b): - return escState.parser.Ground, nil + case sliceContains(escapeIntermediateToGroundBytes, b): + return escState.parser.ground, nil } return escState, nil } -func (escState EscapeIntermediateState) Transition(s State) error { - logger.Infof("EscapeIntermediateState::Transition %s --> %s", escState.Name(), s.Name()) - escState.BaseState.Transition(s) +func (escState escapeIntermediateState) Transition(s state) error { + logger.Infof("escapeIntermediateState::Transition %s --> %s", escState.Name(), s.Name()) + escState.baseState.Transition(s) switch s { - case escState.parser.Ground: + case escState.parser.ground: return escState.parser.escDispatch() } diff --git a/vendor/github.com/Azure/go-ansiterm/escape_state.go b/vendor/github.com/Azure/go-ansiterm/escape_state.go index 232dd8e0d17e..7b1b9ad3f12e 100644 --- a/vendor/github.com/Azure/go-ansiterm/escape_state.go +++ b/vendor/github.com/Azure/go-ansiterm/escape_state.go @@ -1,47 +1,47 @@ package ansiterm -type EscapeState struct { - BaseState +type escapeState struct { + baseState } -func (escState EscapeState) Handle(b byte) (s State, e error) { - logger.Infof("EscapeState::Handle %#x", b) - nextState, err := escState.BaseState.Handle(b) +func (escState escapeState) Handle(b byte) (s state, e error) { + logger.Infof("escapeState::Handle %#x", b) + nextState, err := escState.baseState.Handle(b) if nextState != nil || err != nil { return nextState, err } switch { case b == ANSI_ESCAPE_SECONDARY: - return escState.parser.CsiEntry, nil + return escState.parser.csiEntry, nil case b == ANSI_OSC_STRING_ENTRY: - return escState.parser.OscString, nil - case sliceContains(Executors, b): + return escState.parser.oscString, nil + case sliceContains(executors, b): return escState, escState.parser.execute() - case sliceContains(EscapeToGroundBytes, b): - return escState.parser.Ground, nil - case sliceContains(Intermeds, b): - return escState.parser.EscapeIntermediate, nil + case sliceContains(escapeToGroundBytes, b): + return escState.parser.ground, nil + case sliceContains(intermeds, b): + return escState.parser.escapeIntermediate, nil } return escState, nil } -func (escState EscapeState) Transition(s State) error { +func (escState escapeState) Transition(s state) error { logger.Infof("Escape::Transition %s --> %s", escState.Name(), s.Name()) - escState.BaseState.Transition(s) + escState.baseState.Transition(s) switch s { - case escState.parser.Ground: + case escState.parser.ground: return escState.parser.escDispatch() - case escState.parser.EscapeIntermediate: + case escState.parser.escapeIntermediate: return escState.parser.collectInter() } return nil } -func (escState EscapeState) Enter() error { +func (escState escapeState) Enter() error { escState.parser.clear() return nil } diff --git a/vendor/github.com/Azure/go-ansiterm/ground_state.go b/vendor/github.com/Azure/go-ansiterm/ground_state.go index d600e3e4ae65..52451e94693a 100644 --- a/vendor/github.com/Azure/go-ansiterm/ground_state.go +++ b/vendor/github.com/Azure/go-ansiterm/ground_state.go @@ -1,22 +1,22 @@ package ansiterm -type GroundState struct { - BaseState +type groundState struct { + baseState } -func (gs GroundState) Handle(b byte) (s State, e error) { +func (gs groundState) Handle(b byte) (s state, e error) { gs.parser.context.currentChar = b - nextState, err := gs.BaseState.Handle(b) + nextState, err := gs.baseState.Handle(b) if nextState != nil || err != nil { return nextState, err } switch { - case sliceContains(Printables, b): + case sliceContains(printables, b): return gs, gs.parser.print() - case sliceContains(Executors, b): + case sliceContains(executors, b): return gs, gs.parser.execute() } diff --git a/vendor/github.com/Azure/go-ansiterm/osc_string_state.go b/vendor/github.com/Azure/go-ansiterm/osc_string_state.go index 4490e3cdf6b4..24062d420ebe 100644 --- a/vendor/github.com/Azure/go-ansiterm/osc_string_state.go +++ b/vendor/github.com/Azure/go-ansiterm/osc_string_state.go @@ -1,19 +1,19 @@ package ansiterm -type OscStringState struct { - BaseState +type oscStringState struct { + baseState } -func (oscState OscStringState) Handle(b byte) (s State, e error) { +func (oscState oscStringState) Handle(b byte) (s state, e error) { logger.Infof("OscString::Handle %#x", b) - nextState, err := oscState.BaseState.Handle(b) + nextState, err := oscState.baseState.Handle(b) if nextState != nil || err != nil { return nextState, err } switch { case isOscStringTerminator(b): - return oscState.parser.Ground, nil + return oscState.parser.ground, nil } return oscState, nil diff --git a/vendor/github.com/Azure/go-ansiterm/parser.go b/vendor/github.com/Azure/go-ansiterm/parser.go index ef5e0ad19984..169f68dbefc4 100644 --- a/vendor/github.com/Azure/go-ansiterm/parser.go +++ b/vendor/github.com/Azure/go-ansiterm/parser.go @@ -2,7 +2,6 @@ package ansiterm import ( "errors" - "fmt" "io/ioutil" "os" @@ -12,18 +11,18 @@ import ( var logger *logrus.Logger type AnsiParser struct { - currState State + currState state eventHandler AnsiEventHandler - context *AnsiContext - CsiEntry State - CsiParam State - DcsEntry State - Escape State - EscapeIntermediate State - Error State - Ground State - OscString State - stateMap []State + context *ansiContext + csiEntry state + csiParam state + dcsEntry state + escape state + escapeIntermediate state + error state + ground state + oscString state + stateMap []state } func CreateParser(initialState string, evtHandler AnsiEventHandler) *AnsiParser { @@ -41,27 +40,27 @@ func CreateParser(initialState string, evtHandler AnsiEventHandler) *AnsiParser parser := &AnsiParser{ eventHandler: evtHandler, - context: &AnsiContext{}, + context: &ansiContext{}, } - parser.CsiEntry = CsiEntryState{BaseState{name: "CsiEntry", parser: parser}} - parser.CsiParam = CsiParamState{BaseState{name: "CsiParam", parser: parser}} - parser.DcsEntry = DcsEntryState{BaseState{name: "DcsEntry", parser: parser}} - parser.Escape = EscapeState{BaseState{name: "Escape", parser: parser}} - parser.EscapeIntermediate = EscapeIntermediateState{BaseState{name: "EscapeIntermediate", parser: parser}} - parser.Error = ErrorState{BaseState{name: "Error", parser: parser}} - parser.Ground = GroundState{BaseState{name: "Ground", parser: parser}} - parser.OscString = OscStringState{BaseState{name: "OscString", parser: parser}} - - parser.stateMap = []State{ - parser.CsiEntry, - parser.CsiParam, - parser.DcsEntry, - parser.Escape, - parser.EscapeIntermediate, - parser.Error, - parser.Ground, - parser.OscString, + parser.csiEntry = csiEntryState{baseState{name: "CsiEntry", parser: parser}} + parser.csiParam = csiParamState{baseState{name: "CsiParam", parser: parser}} + parser.dcsEntry = dcsEntryState{baseState{name: "DcsEntry", parser: parser}} + parser.escape = escapeState{baseState{name: "Escape", parser: parser}} + parser.escapeIntermediate = escapeIntermediateState{baseState{name: "EscapeIntermediate", parser: parser}} + parser.error = errorState{baseState{name: "Error", parser: parser}} + parser.ground = groundState{baseState{name: "Ground", parser: parser}} + parser.oscString = oscStringState{baseState{name: "OscString", parser: parser}} + + parser.stateMap = []state{ + parser.csiEntry, + parser.csiParam, + parser.dcsEntry, + parser.escape, + parser.escapeIntermediate, + parser.error, + parser.ground, + parser.oscString, } parser.currState = getState(initialState, parser.stateMap) @@ -70,7 +69,7 @@ func CreateParser(initialState string, evtHandler AnsiEventHandler) *AnsiParser return parser } -func getState(name string, states []State) State { +func getState(name string, states []state) state { for _, el := range states { if el.Name() == name { return el @@ -99,7 +98,7 @@ func (ap *AnsiParser) handle(b byte) error { if newState == nil { logger.Warning("newState is nil") - return errors.New(fmt.Sprintf("New state of 'nil' is invalid.")) + return errors.New("New state of 'nil' is invalid.") } if newState != ap.currState { @@ -111,7 +110,7 @@ func (ap *AnsiParser) handle(b byte) error { return nil } -func (ap *AnsiParser) changeState(newState State) error { +func (ap *AnsiParser) changeState(newState state) error { logger.Infof("ChangeState %s --> %s", ap.currState.Name(), newState.Name()) // Exit old state diff --git a/vendor/github.com/Azure/go-ansiterm/parser_action_helpers.go b/vendor/github.com/Azure/go-ansiterm/parser_action_helpers.go index 438802097ddb..8b69a67a5aa1 100644 --- a/vendor/github.com/Azure/go-ansiterm/parser_action_helpers.go +++ b/vendor/github.com/Azure/go-ansiterm/parser_action_helpers.go @@ -31,7 +31,7 @@ func parseParams(bytes []byte) ([]string, error) { return params, nil } -func parseCmd(context AnsiContext) (string, error) { +func parseCmd(context ansiContext) (string, error) { return string(context.currentChar), nil } diff --git a/vendor/github.com/Azure/go-ansiterm/parser_actions.go b/vendor/github.com/Azure/go-ansiterm/parser_actions.go index 260e6aae3c52..58750a2d2b1b 100644 --- a/vendor/github.com/Azure/go-ansiterm/parser_actions.go +++ b/vendor/github.com/Azure/go-ansiterm/parser_actions.go @@ -113,7 +113,7 @@ func (ap *AnsiParser) print() error { } func (ap *AnsiParser) clear() error { - ap.context = &AnsiContext{} + ap.context = &ansiContext{} return nil } diff --git a/vendor/github.com/Azure/go-ansiterm/parser_test_helpers.go b/vendor/github.com/Azure/go-ansiterm/parser_test_helpers.go deleted file mode 100644 index 562f215d342d..000000000000 --- a/vendor/github.com/Azure/go-ansiterm/parser_test_helpers.go +++ /dev/null @@ -1,114 +0,0 @@ -package ansiterm - -import ( - "fmt" - "testing" -) - -func getStateNames() []string { - parser, _ := createTestParser("Ground") - - stateNames := []string{} - for _, state := range parser.stateMap { - stateNames = append(stateNames, state.Name()) - } - - return stateNames -} - -func stateTransitionHelper(t *testing.T, start string, end string, bytes []byte) { - for _, b := range bytes { - bytes := []byte{byte(b)} - parser, _ := createTestParser(start) - parser.Parse(bytes) - validateState(t, parser.currState, end) - } -} - -func anyToXHelper(t *testing.T, bytes []byte, expectedState string) { - for _, s := range getStateNames() { - stateTransitionHelper(t, s, expectedState, bytes) - } -} - -func funcCallParamHelper(t *testing.T, bytes []byte, start string, expected string, expectedCalls []string) { - parser, evtHandler := createTestParser(start) - parser.Parse(bytes) - validateState(t, parser.currState, expected) - validateFuncCalls(t, evtHandler.FunctionCalls, expectedCalls) -} - -func parseParamsHelper(t *testing.T, bytes []byte, expectedParams []string) { - params, err := parseParams(bytes) - - if err != nil { - t.Errorf("Parameter parse error: %v", err) - return - } - - if len(params) != len(expectedParams) { - t.Errorf("Parsed parameters: %v", params) - t.Errorf("Expected parameters: %v", expectedParams) - t.Errorf("Parameter length failure: %d != %d", len(params), len(expectedParams)) - return - } - - for i, v := range expectedParams { - if v != params[i] { - t.Errorf("Parsed parameters: %v", params) - t.Errorf("Expected parameters: %v", expectedParams) - t.Errorf("Parameter parse failure: %s != %s at position %d", v, params[i], i) - } - } -} - -func cursorSingleParamHelper(t *testing.T, command byte, funcName string) { - funcCallParamHelper(t, []byte{command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1])", funcName)}) - funcCallParamHelper(t, []byte{'0', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1])", funcName)}) - funcCallParamHelper(t, []byte{'2', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([2])", funcName)}) - funcCallParamHelper(t, []byte{'2', '3', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([23])", funcName)}) - funcCallParamHelper(t, []byte{'2', ';', '3', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([2])", funcName)}) - funcCallParamHelper(t, []byte{'2', ';', '3', ';', '4', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([2])", funcName)}) -} - -func cursorTwoParamHelper(t *testing.T, command byte, funcName string) { - funcCallParamHelper(t, []byte{command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1 1])", funcName)}) - funcCallParamHelper(t, []byte{'0', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1 1])", funcName)}) - funcCallParamHelper(t, []byte{'2', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([2 1])", funcName)}) - funcCallParamHelper(t, []byte{'2', '3', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([23 1])", funcName)}) - funcCallParamHelper(t, []byte{'2', ';', '3', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([2 3])", funcName)}) - funcCallParamHelper(t, []byte{'2', ';', '3', ';', '4', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([2 3])", funcName)}) -} - -func eraseHelper(t *testing.T, command byte, funcName string) { - funcCallParamHelper(t, []byte{command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([0])", funcName)}) - funcCallParamHelper(t, []byte{'0', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([0])", funcName)}) - funcCallParamHelper(t, []byte{'1', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1])", funcName)}) - funcCallParamHelper(t, []byte{'2', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([2])", funcName)}) - funcCallParamHelper(t, []byte{'3', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([3])", funcName)}) - funcCallParamHelper(t, []byte{'4', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([0])", funcName)}) - funcCallParamHelper(t, []byte{'1', ';', '2', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1])", funcName)}) -} - -func scrollHelper(t *testing.T, command byte, funcName string) { - funcCallParamHelper(t, []byte{command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1])", funcName)}) - funcCallParamHelper(t, []byte{'0', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1])", funcName)}) - funcCallParamHelper(t, []byte{'1', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1])", funcName)}) - funcCallParamHelper(t, []byte{'5', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([5])", funcName)}) - funcCallParamHelper(t, []byte{'4', ';', '6', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([4])", funcName)}) -} - -func clearOnStateChangeHelper(t *testing.T, start string, end string, bytes []byte) { - p, _ := createTestParser(start) - fillContext(p.context) - p.Parse(bytes) - validateState(t, p.currState, end) - validateEmptyContext(t, p.context) -} - -func c0Helper(t *testing.T, bytes []byte, expectedState string, expectedCalls []string) { - parser, evtHandler := createTestParser("Ground") - parser.Parse(bytes) - validateState(t, parser.currState, expectedState) - validateFuncCalls(t, evtHandler.FunctionCalls, expectedCalls) -} diff --git a/vendor/github.com/Azure/go-ansiterm/parser_test_utilities.go b/vendor/github.com/Azure/go-ansiterm/parser_test_utilities.go deleted file mode 100644 index 51d1d49bf03f..000000000000 --- a/vendor/github.com/Azure/go-ansiterm/parser_test_utilities.go +++ /dev/null @@ -1,66 +0,0 @@ -package ansiterm - -import ( - "testing" -) - -func createTestParser(s string) (*AnsiParser, *TestAnsiEventHandler) { - evtHandler := CreateTestAnsiEventHandler() - parser := CreateParser(s, evtHandler) - - return parser, evtHandler -} - -func validateState(t *testing.T, actualState State, expectedStateName string) { - actualName := "Nil" - - if actualState != nil { - actualName = actualState.Name() - } - - if actualName != expectedStateName { - t.Errorf("Invalid State: '%s' != '%s'", actualName, expectedStateName) - } -} - -func validateFuncCalls(t *testing.T, actualCalls []string, expectedCalls []string) { - actualCount := len(actualCalls) - expectedCount := len(expectedCalls) - - if actualCount != expectedCount { - t.Errorf("Actual calls: %v", actualCalls) - t.Errorf("Expected calls: %v", expectedCalls) - t.Errorf("Call count error: %d != %d", actualCount, expectedCount) - return - } - - for i, v := range actualCalls { - if v != expectedCalls[i] { - t.Errorf("Actual calls: %v", actualCalls) - t.Errorf("Expected calls: %v", expectedCalls) - t.Errorf("Mismatched calls: %s != %s with lengths %d and %d", v, expectedCalls[i], len(v), len(expectedCalls[i])) - } - } -} - -func fillContext(context *AnsiContext) { - context.currentChar = 'A' - context.paramBuffer = []byte{'C', 'D', 'E'} - context.interBuffer = []byte{'F', 'G', 'H'} -} - -func validateEmptyContext(t *testing.T, context *AnsiContext) { - var expectedCurrChar byte = 0x0 - if context.currentChar != expectedCurrChar { - t.Errorf("Currentchar mismatch '%#x' != '%#x'", context.currentChar, expectedCurrChar) - } - - if len(context.paramBuffer) != 0 { - t.Errorf("Non-empty parameter buffer: %v", context.paramBuffer) - } - - if len(context.paramBuffer) != 0 { - t.Errorf("Non-empty intermediate buffer: %v", context.interBuffer) - } - -} diff --git a/vendor/github.com/Azure/go-ansiterm/states.go b/vendor/github.com/Azure/go-ansiterm/states.go index 0cbdcb3c8345..f2ea1fcd12da 100644 --- a/vendor/github.com/Azure/go-ansiterm/states.go +++ b/vendor/github.com/Azure/go-ansiterm/states.go @@ -1,52 +1,52 @@ package ansiterm -type StateId int +type stateID int -type State interface { +type state interface { Enter() error Exit() error - Handle(byte) (State, error) + Handle(byte) (state, error) Name() string - Transition(State) error + Transition(state) error } -type BaseState struct { +type baseState struct { name string parser *AnsiParser } -func (base BaseState) Enter() error { +func (base baseState) Enter() error { return nil } -func (base BaseState) Exit() error { +func (base baseState) Exit() error { return nil } -func (base BaseState) Handle(b byte) (s State, e error) { +func (base baseState) Handle(b byte) (s state, e error) { switch { case b == CSI_ENTRY: - return base.parser.CsiEntry, nil + return base.parser.csiEntry, nil case b == DCS_ENTRY: - return base.parser.DcsEntry, nil + return base.parser.dcsEntry, nil case b == ANSI_ESCAPE_PRIMARY: - return base.parser.Escape, nil + return base.parser.escape, nil case b == OSC_STRING: - return base.parser.OscString, nil - case sliceContains(ToGroundBytes, b): - return base.parser.Ground, nil + return base.parser.oscString, nil + case sliceContains(toGroundBytes, b): + return base.parser.ground, nil } return nil, nil } -func (base BaseState) Name() string { +func (base baseState) Name() string { return base.name } -func (base BaseState) Transition(s State) error { - if s == base.parser.Ground { +func (base baseState) Transition(s state) error { + if s == base.parser.ground { execBytes := []byte{0x18} execBytes = append(execBytes, 0x1A) execBytes = append(execBytes, getByteRange(0x80, 0x8F)...) @@ -62,10 +62,10 @@ func (base BaseState) Transition(s State) error { return nil } -type DcsEntryState struct { - BaseState +type dcsEntryState struct { + baseState } -type ErrorState struct { - BaseState +type errorState struct { + baseState } diff --git a/vendor/github.com/Azure/go-ansiterm/test_event_handler.go b/vendor/github.com/Azure/go-ansiterm/test_event_handler.go deleted file mode 100644 index 60f9f30b98d7..000000000000 --- a/vendor/github.com/Azure/go-ansiterm/test_event_handler.go +++ /dev/null @@ -1,173 +0,0 @@ -package ansiterm - -import ( - "fmt" - "strconv" -) - -type TestAnsiEventHandler struct { - FunctionCalls []string -} - -func CreateTestAnsiEventHandler() *TestAnsiEventHandler { - evtHandler := TestAnsiEventHandler{} - evtHandler.FunctionCalls = make([]string, 0) - return &evtHandler -} - -func (h *TestAnsiEventHandler) recordCall(call string, params []string) { - s := fmt.Sprintf("%s(%v)", call, params) - h.FunctionCalls = append(h.FunctionCalls, s) -} - -func (h *TestAnsiEventHandler) Print(b byte) error { - h.recordCall("Print", []string{string(b)}) - return nil -} - -func (h *TestAnsiEventHandler) Execute(b byte) error { - h.recordCall("Execute", []string{string(b)}) - return nil -} - -func (h *TestAnsiEventHandler) CUU(param int) error { - h.recordCall("CUU", []string{strconv.Itoa(param)}) - return nil -} - -func (h *TestAnsiEventHandler) CUD(param int) error { - h.recordCall("CUD", []string{strconv.Itoa(param)}) - return nil -} - -func (h *TestAnsiEventHandler) CUF(param int) error { - h.recordCall("CUF", []string{strconv.Itoa(param)}) - return nil -} - -func (h *TestAnsiEventHandler) CUB(param int) error { - h.recordCall("CUB", []string{strconv.Itoa(param)}) - return nil -} - -func (h *TestAnsiEventHandler) CNL(param int) error { - h.recordCall("CNL", []string{strconv.Itoa(param)}) - return nil -} - -func (h *TestAnsiEventHandler) CPL(param int) error { - h.recordCall("CPL", []string{strconv.Itoa(param)}) - return nil -} - -func (h *TestAnsiEventHandler) CHA(param int) error { - h.recordCall("CHA", []string{strconv.Itoa(param)}) - return nil -} - -func (h *TestAnsiEventHandler) VPA(param int) error { - h.recordCall("VPA", []string{strconv.Itoa(param)}) - return nil -} - -func (h *TestAnsiEventHandler) CUP(x int, y int) error { - xS, yS := strconv.Itoa(x), strconv.Itoa(y) - h.recordCall("CUP", []string{xS, yS}) - return nil -} - -func (h *TestAnsiEventHandler) HVP(x int, y int) error { - xS, yS := strconv.Itoa(x), strconv.Itoa(y) - h.recordCall("HVP", []string{xS, yS}) - return nil -} - -func (h *TestAnsiEventHandler) DECTCEM(visible bool) error { - h.recordCall("DECTCEM", []string{strconv.FormatBool(visible)}) - return nil -} - -func (h *TestAnsiEventHandler) DECOM(visible bool) error { - h.recordCall("DECOM", []string{strconv.FormatBool(visible)}) - return nil -} - -func (h *TestAnsiEventHandler) DECCOLM(use132 bool) error { - h.recordCall("DECOLM", []string{strconv.FormatBool(use132)}) - return nil -} - -func (h *TestAnsiEventHandler) ED(param int) error { - h.recordCall("ED", []string{strconv.Itoa(param)}) - return nil -} - -func (h *TestAnsiEventHandler) EL(param int) error { - h.recordCall("EL", []string{strconv.Itoa(param)}) - return nil -} - -func (h *TestAnsiEventHandler) IL(param int) error { - h.recordCall("IL", []string{strconv.Itoa(param)}) - return nil -} - -func (h *TestAnsiEventHandler) DL(param int) error { - h.recordCall("DL", []string{strconv.Itoa(param)}) - return nil -} - -func (h *TestAnsiEventHandler) ICH(param int) error { - h.recordCall("ICH", []string{strconv.Itoa(param)}) - return nil -} - -func (h *TestAnsiEventHandler) DCH(param int) error { - h.recordCall("DCH", []string{strconv.Itoa(param)}) - return nil -} - -func (h *TestAnsiEventHandler) SGR(params []int) error { - strings := []string{} - for _, v := range params { - strings = append(strings, strconv.Itoa(v)) - } - - h.recordCall("SGR", strings) - return nil -} - -func (h *TestAnsiEventHandler) SU(param int) error { - h.recordCall("SU", []string{strconv.Itoa(param)}) - return nil -} - -func (h *TestAnsiEventHandler) SD(param int) error { - h.recordCall("SD", []string{strconv.Itoa(param)}) - return nil -} - -func (h *TestAnsiEventHandler) DA(params []string) error { - h.recordCall("DA", params) - return nil -} - -func (h *TestAnsiEventHandler) DECSTBM(top int, bottom int) error { - topS, bottomS := strconv.Itoa(top), strconv.Itoa(bottom) - h.recordCall("DECSTBM", []string{topS, bottomS}) - return nil -} - -func (h *TestAnsiEventHandler) RI() error { - h.recordCall("RI", nil) - return nil -} - -func (h *TestAnsiEventHandler) IND() error { - h.recordCall("IND", nil) - return nil -} - -func (h *TestAnsiEventHandler) Flush() error { - return nil -} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go b/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go index 78fe92fe65f1..daf2f0696158 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go @@ -9,7 +9,7 @@ import ( "strings" "syscall" - . "github.com/Azure/go-ansiterm" + "github.com/Azure/go-ansiterm" ) // Windows keyboard constants @@ -85,17 +85,17 @@ func newAnsiCommand(command []byte) *ansiCommand { if lastCharIndex != 0 { start := 1 // skip if double char escape sequence - if command[0] == ANSI_ESCAPE_PRIMARY && command[1] == ANSI_ESCAPE_SECONDARY { + if command[0] == ansiterm.ANSI_ESCAPE_PRIMARY && command[1] == ansiterm.ANSI_ESCAPE_SECONDARY { start++ } // convert this to GetNextParam method - ac.Parameters = strings.Split(string(command[start:lastCharIndex]), ANSI_PARAMETER_SEP) + ac.Parameters = strings.Split(string(command[start:lastCharIndex]), ansiterm.ANSI_PARAMETER_SEP) } return ac } -func (ac *ansiCommand) paramAsSHORT(index int, defaultValue SHORT) SHORT { +func (ac *ansiCommand) paramAsSHORT(index int, defaultValue int16) int16 { if index < 0 || index >= len(ac.Parameters) { return defaultValue } @@ -105,7 +105,7 @@ func (ac *ansiCommand) paramAsSHORT(index int, defaultValue SHORT) SHORT { return defaultValue } - return SHORT(param) + return int16(param) } func (ac *ansiCommand) String() string { @@ -119,12 +119,12 @@ func (ac *ansiCommand) String() string { // See http://manpages.ubuntu.com/manpages/intrepid/man4/console_codes.4.html. func isAnsiCommandChar(b byte) bool { switch { - case ANSI_COMMAND_FIRST <= b && b <= ANSI_COMMAND_LAST && b != ANSI_ESCAPE_SECONDARY: + case ansiterm.ANSI_COMMAND_FIRST <= b && b <= ansiterm.ANSI_COMMAND_LAST && b != ansiterm.ANSI_ESCAPE_SECONDARY: return true - case b == ANSI_CMD_G1 || b == ANSI_CMD_OSC || b == ANSI_CMD_DECPAM || b == ANSI_CMD_DECPNM: + case b == ansiterm.ANSI_CMD_G1 || b == ansiterm.ANSI_CMD_OSC || b == ansiterm.ANSI_CMD_DECPAM || b == ansiterm.ANSI_CMD_DECPNM: // non-CSI escape sequence terminator return true - case b == ANSI_CMD_STR_TERM || b == ANSI_BEL: + case b == ansiterm.ANSI_CMD_STR_TERM || b == ansiterm.ANSI_BEL: // String escape sequence terminator return true } @@ -132,11 +132,11 @@ func isAnsiCommandChar(b byte) bool { } func isXtermOscSequence(command []byte, current byte) bool { - return (len(command) >= 2 && command[0] == ANSI_ESCAPE_PRIMARY && command[1] == ANSI_CMD_OSC && current != ANSI_BEL) + return (len(command) >= 2 && command[0] == ansiterm.ANSI_ESCAPE_PRIMARY && command[1] == ansiterm.ANSI_CMD_OSC && current != ansiterm.ANSI_BEL) } func isCharacterSelectionCmdChar(b byte) bool { - return (b == ANSI_CMD_G0 || b == ANSI_CMD_G1 || b == ANSI_CMD_G2 || b == ANSI_CMD_G3) + return (b == ansiterm.ANSI_CMD_G0 || b == ansiterm.ANSI_CMD_G1 || b == ansiterm.ANSI_CMD_G2 || b == ansiterm.ANSI_CMD_G3) } // bytesToHex converts a slice of bytes to a human-readable string. @@ -150,7 +150,7 @@ func bytesToHex(b []byte) string { // ensureInRange adjusts the passed value, if necessary, to ensure it is within // the passed min / max range. -func ensureInRange(n SHORT, min SHORT, max SHORT) SHORT { +func ensureInRange(n int16, min int16, max int16) int16 { if n < min { return min } else if n > max { diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/api.go b/vendor/github.com/Azure/go-ansiterm/winterm/api.go index 1f2f3853cc4e..462d92f8ef9f 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/api.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/api.go @@ -66,21 +66,21 @@ const ( // -- The attributes are combined to produce various colors (e.g., Blue + Green will create Cyan). // Clearing all foreground or background colors results in black; setting all creates white. // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms682088(v=vs.85).aspx#_win32_character_attributes. - FOREGROUND_BLUE WORD = 0x0001 - FOREGROUND_GREEN WORD = 0x0002 - FOREGROUND_RED WORD = 0x0004 - FOREGROUND_INTENSITY WORD = 0x0008 - FOREGROUND_MASK WORD = 0x000F - - BACKGROUND_BLUE WORD = 0x0010 - BACKGROUND_GREEN WORD = 0x0020 - BACKGROUND_RED WORD = 0x0040 - BACKGROUND_INTENSITY WORD = 0x0080 - BACKGROUND_MASK WORD = 0x00F0 - - COMMON_LVB_MASK WORD = 0xFF00 - COMMON_LVB_REVERSE_VIDEO WORD = 0x4000 - COMMON_LVB_UNDERSCORE WORD = 0x8000 + FOREGROUND_BLUE uint16 = 0x0001 + FOREGROUND_GREEN uint16 = 0x0002 + FOREGROUND_RED uint16 = 0x0004 + FOREGROUND_INTENSITY uint16 = 0x0008 + FOREGROUND_MASK uint16 = 0x000F + + BACKGROUND_BLUE uint16 = 0x0010 + BACKGROUND_GREEN uint16 = 0x0020 + BACKGROUND_RED uint16 = 0x0040 + BACKGROUND_INTENSITY uint16 = 0x0080 + BACKGROUND_MASK uint16 = 0x00F0 + + COMMON_LVB_MASK uint16 = 0xFF00 + COMMON_LVB_REVERSE_VIDEO uint16 = 0x4000 + COMMON_LVB_UNDERSCORE uint16 = 0x8000 // Input event types // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms683499(v=vs.85).aspx. @@ -104,60 +104,53 @@ const ( ) // Windows API Console types -// -- See https://msdn.microsoft.com/en-us/library/windows/desktop/aa383751(v=vs.85).aspx for core types (e.g., SHORT) // -- See https://msdn.microsoft.com/en-us/library/windows/desktop/ms682101(v=vs.85).aspx for Console specific types (e.g., COORD) // -- See https://msdn.microsoft.com/en-us/library/aa296569(v=vs.60).aspx for comments on alignment type ( - SHORT int16 - BOOL int32 - WORD uint16 - WCHAR uint16 - DWORD uint32 - CHAR_INFO struct { - UnicodeChar WCHAR - Attributes WORD + UnicodeChar uint16 + Attributes uint16 } CONSOLE_CURSOR_INFO struct { - Size DWORD - Visible BOOL + Size uint32 + Visible int32 } CONSOLE_SCREEN_BUFFER_INFO struct { Size COORD CursorPosition COORD - Attributes WORD + Attributes uint16 Window SMALL_RECT MaximumWindowSize COORD } COORD struct { - X SHORT - Y SHORT + X int16 + Y int16 } SMALL_RECT struct { - Left SHORT - Top SHORT - Right SHORT - Bottom SHORT + Left int16 + Top int16 + Right int16 + Bottom int16 } // INPUT_RECORD is a C/C++ union of which KEY_EVENT_RECORD is one case, it is also the largest // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms683499(v=vs.85).aspx. INPUT_RECORD struct { - EventType WORD + EventType uint16 KeyEvent KEY_EVENT_RECORD } KEY_EVENT_RECORD struct { - KeyDown BOOL - RepeatCount WORD - VirtualKeyCode WORD - VirtualScanCode WORD - UnicodeChar WCHAR - ControlKeyState DWORD + KeyDown int32 + RepeatCount uint16 + VirtualKeyCode uint16 + VirtualScanCode uint16 + UnicodeChar uint16 + ControlKeyState uint32 } WINDOW_BUFFER_SIZE struct { @@ -165,12 +158,12 @@ type ( } ) -// boolToBOOL converts a Go bool into a Windows BOOL. -func boolToBOOL(f bool) BOOL { +// boolToBOOL converts a Go bool into a Windows int32. +func boolToBOOL(f bool) int32 { if f { - return BOOL(1) + return int32(1) } else { - return BOOL(0) + return int32(0) } } @@ -242,7 +235,7 @@ func SetConsoleScreenBufferSize(handle uintptr, coord COORD) error { // SetConsoleTextAttribute sets the attributes of characters written to the // console screen buffer by the WriteFile or WriteConsole function. // See http://msdn.microsoft.com/en-us/library/windows/desktop/ms686047(v=vs.85).aspx. -func SetConsoleTextAttribute(handle uintptr, attribute WORD) error { +func SetConsoleTextAttribute(handle uintptr, attribute uint16) error { r1, r2, err := setConsoleTextAttributeProc.Call(handle, uintptr(attribute), 0) use(attribute) return checkError(r1, r2, err) @@ -280,7 +273,7 @@ func ReadConsoleInput(handle uintptr, buffer []INPUT_RECORD, count *uint32) erro // It returns true if the handle was signaled; false otherwise. // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms687032(v=vs.85).aspx. func WaitForSingleObject(handle uintptr, msWait uint32) (bool, error) { - r1, _, err := waitForSingleObjectProc.Call(handle, uintptr(DWORD(msWait))) + r1, _, err := waitForSingleObjectProc.Call(handle, uintptr(uint32(msWait))) switch r1 { case WAIT_ABANDONED, WAIT_TIMEOUT: return false, nil @@ -320,8 +313,8 @@ func checkError(r1, r2 uintptr, err error) error { // coordToPointer converts a COORD into a uintptr (by fooling the type system). func coordToPointer(c COORD) uintptr { - // Note: This code assumes the two SHORTs are correctly laid out; the "cast" to DWORD is just to get a pointer to pass. - return uintptr(*((*DWORD)(unsafe.Pointer(&c)))) + // Note: This code assumes the two SHORTs are correctly laid out; the "cast" to uint32 is just to get a pointer to pass. + return uintptr(*((*uint32)(unsafe.Pointer(&c)))) } // use is a no-op, but the compiler cannot see that it is. diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go b/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go index 94665db6fb0c..cbec8f728f49 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go @@ -2,9 +2,7 @@ package winterm -import ( - . "github.com/Azure/go-ansiterm" -) +import "github.com/Azure/go-ansiterm" const ( FOREGROUND_COLOR_MASK = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE @@ -13,83 +11,83 @@ const ( // collectAnsiIntoWindowsAttributes modifies the passed Windows text mode flags to reflect the // request represented by the passed ANSI mode. -func collectAnsiIntoWindowsAttributes(windowsMode WORD, inverted bool, baseMode WORD, ansiMode SHORT) (WORD, bool) { +func collectAnsiIntoWindowsAttributes(windowsMode uint16, inverted bool, baseMode uint16, ansiMode int16) (uint16, bool) { switch ansiMode { // Mode styles - case ANSI_SGR_BOLD: + case ansiterm.ANSI_SGR_BOLD: windowsMode = windowsMode | FOREGROUND_INTENSITY - case ANSI_SGR_DIM, ANSI_SGR_BOLD_DIM_OFF: + case ansiterm.ANSI_SGR_DIM, ansiterm.ANSI_SGR_BOLD_DIM_OFF: windowsMode &^= FOREGROUND_INTENSITY - case ANSI_SGR_UNDERLINE: + case ansiterm.ANSI_SGR_UNDERLINE: windowsMode = windowsMode | COMMON_LVB_UNDERSCORE - case ANSI_SGR_REVERSE: + case ansiterm.ANSI_SGR_REVERSE: inverted = true - case ANSI_SGR_REVERSE_OFF: + case ansiterm.ANSI_SGR_REVERSE_OFF: inverted = false - case ANSI_SGR_UNDERLINE_OFF: + case ansiterm.ANSI_SGR_UNDERLINE_OFF: windowsMode &^= COMMON_LVB_UNDERSCORE // Foreground colors - case ANSI_SGR_FOREGROUND_DEFAULT: + case ansiterm.ANSI_SGR_FOREGROUND_DEFAULT: windowsMode = (windowsMode &^ FOREGROUND_MASK) | (baseMode & FOREGROUND_MASK) - case ANSI_SGR_FOREGROUND_BLACK: + case ansiterm.ANSI_SGR_FOREGROUND_BLACK: windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) - case ANSI_SGR_FOREGROUND_RED: + case ansiterm.ANSI_SGR_FOREGROUND_RED: windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED - case ANSI_SGR_FOREGROUND_GREEN: + case ansiterm.ANSI_SGR_FOREGROUND_GREEN: windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_GREEN - case ANSI_SGR_FOREGROUND_YELLOW: + case ansiterm.ANSI_SGR_FOREGROUND_YELLOW: windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED | FOREGROUND_GREEN - case ANSI_SGR_FOREGROUND_BLUE: + case ansiterm.ANSI_SGR_FOREGROUND_BLUE: windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_BLUE - case ANSI_SGR_FOREGROUND_MAGENTA: + case ansiterm.ANSI_SGR_FOREGROUND_MAGENTA: windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED | FOREGROUND_BLUE - case ANSI_SGR_FOREGROUND_CYAN: + case ansiterm.ANSI_SGR_FOREGROUND_CYAN: windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_GREEN | FOREGROUND_BLUE - case ANSI_SGR_FOREGROUND_WHITE: + case ansiterm.ANSI_SGR_FOREGROUND_WHITE: windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE // Background colors - case ANSI_SGR_BACKGROUND_DEFAULT: + case ansiterm.ANSI_SGR_BACKGROUND_DEFAULT: // Black with no intensity windowsMode = (windowsMode &^ BACKGROUND_MASK) | (baseMode & BACKGROUND_MASK) - case ANSI_SGR_BACKGROUND_BLACK: + case ansiterm.ANSI_SGR_BACKGROUND_BLACK: windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) - case ANSI_SGR_BACKGROUND_RED: + case ansiterm.ANSI_SGR_BACKGROUND_RED: windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED - case ANSI_SGR_BACKGROUND_GREEN: + case ansiterm.ANSI_SGR_BACKGROUND_GREEN: windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_GREEN - case ANSI_SGR_BACKGROUND_YELLOW: + case ansiterm.ANSI_SGR_BACKGROUND_YELLOW: windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED | BACKGROUND_GREEN - case ANSI_SGR_BACKGROUND_BLUE: + case ansiterm.ANSI_SGR_BACKGROUND_BLUE: windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_BLUE - case ANSI_SGR_BACKGROUND_MAGENTA: + case ansiterm.ANSI_SGR_BACKGROUND_MAGENTA: windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED | BACKGROUND_BLUE - case ANSI_SGR_BACKGROUND_CYAN: + case ansiterm.ANSI_SGR_BACKGROUND_CYAN: windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_GREEN | BACKGROUND_BLUE - case ANSI_SGR_BACKGROUND_WHITE: + case ansiterm.ANSI_SGR_BACKGROUND_WHITE: windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE } @@ -97,6 +95,6 @@ func collectAnsiIntoWindowsAttributes(windowsMode WORD, inverted bool, baseMode } // invertAttributes inverts the foreground and background colors of a Windows attributes value -func invertAttributes(windowsMode WORD) WORD { +func invertAttributes(windowsMode uint16) uint16 { return (COMMON_LVB_MASK & windowsMode) | ((FOREGROUND_MASK & windowsMode) << 4) | ((BACKGROUND_MASK & windowsMode) >> 4) } diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go b/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go index e4b1c255a463..f015723ade79 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go @@ -3,11 +3,11 @@ package winterm const ( - Horizontal = iota - Vertical + horizontal = iota + vertical ) -func (h *WindowsAnsiEventHandler) getCursorWindow(info *CONSOLE_SCREEN_BUFFER_INFO) SMALL_RECT { +func (h *windowsAnsiEventHandler) getCursorWindow(info *CONSOLE_SCREEN_BUFFER_INFO) SMALL_RECT { if h.originMode { sr := h.effectiveSr(info.Window) return SMALL_RECT{ @@ -27,7 +27,7 @@ func (h *WindowsAnsiEventHandler) getCursorWindow(info *CONSOLE_SCREEN_BUFFER_IN } // setCursorPosition sets the cursor to the specified position, bounded to the screen size -func (h *WindowsAnsiEventHandler) setCursorPosition(position COORD, window SMALL_RECT) error { +func (h *windowsAnsiEventHandler) setCursorPosition(position COORD, window SMALL_RECT) error { position.X = ensureInRange(position.X, window.Left, window.Right) position.Y = ensureInRange(position.Y, window.Top, window.Bottom) err := SetConsoleCursorPosition(h.fd, position) @@ -38,15 +38,15 @@ func (h *WindowsAnsiEventHandler) setCursorPosition(position COORD, window SMALL return err } -func (h *WindowsAnsiEventHandler) moveCursorVertical(param int) error { - return h.moveCursor(Vertical, param) +func (h *windowsAnsiEventHandler) moveCursorVertical(param int) error { + return h.moveCursor(vertical, param) } -func (h *WindowsAnsiEventHandler) moveCursorHorizontal(param int) error { - return h.moveCursor(Horizontal, param) +func (h *windowsAnsiEventHandler) moveCursorHorizontal(param int) error { + return h.moveCursor(horizontal, param) } -func (h *WindowsAnsiEventHandler) moveCursor(moveMode int, param int) error { +func (h *windowsAnsiEventHandler) moveCursor(moveMode int, param int) error { info, err := GetConsoleScreenBufferInfo(h.fd) if err != nil { return err @@ -54,10 +54,10 @@ func (h *WindowsAnsiEventHandler) moveCursor(moveMode int, param int) error { position := info.CursorPosition switch moveMode { - case Horizontal: - position.X += SHORT(param) - case Vertical: - position.Y += SHORT(param) + case horizontal: + position.X += int16(param) + case vertical: + position.Y += int16(param) } if err = h.setCursorPosition(position, h.getCursorWindow(info)); err != nil { @@ -67,7 +67,7 @@ func (h *WindowsAnsiEventHandler) moveCursor(moveMode int, param int) error { return nil } -func (h *WindowsAnsiEventHandler) moveCursorLine(param int) error { +func (h *windowsAnsiEventHandler) moveCursorLine(param int) error { info, err := GetConsoleScreenBufferInfo(h.fd) if err != nil { return err @@ -75,7 +75,7 @@ func (h *WindowsAnsiEventHandler) moveCursorLine(param int) error { position := info.CursorPosition position.X = 0 - position.Y += SHORT(param) + position.Y += int16(param) if err = h.setCursorPosition(position, h.getCursorWindow(info)); err != nil { return err @@ -84,14 +84,14 @@ func (h *WindowsAnsiEventHandler) moveCursorLine(param int) error { return nil } -func (h *WindowsAnsiEventHandler) moveCursorColumn(param int) error { +func (h *windowsAnsiEventHandler) moveCursorColumn(param int) error { info, err := GetConsoleScreenBufferInfo(h.fd) if err != nil { return err } position := info.CursorPosition - position.X = SHORT(param) - 1 + position.X = int16(param) - 1 if err = h.setCursorPosition(position, h.getCursorWindow(info)); err != nil { return err diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go b/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go index f02a5b261b54..244b5fa25efb 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go @@ -2,11 +2,9 @@ package winterm -import ( - . "github.com/Azure/go-ansiterm" -) +import "github.com/Azure/go-ansiterm" -func (h *WindowsAnsiEventHandler) clearRange(attributes WORD, fromCoord COORD, toCoord COORD) error { +func (h *windowsAnsiEventHandler) clearRange(attributes uint16, fromCoord COORD, toCoord COORD) error { // Ignore an invalid (negative area) request if toCoord.Y < fromCoord.Y { return nil @@ -60,7 +58,7 @@ func (h *WindowsAnsiEventHandler) clearRange(attributes WORD, fromCoord COORD, t return nil } -func (h *WindowsAnsiEventHandler) clearRect(attributes WORD, fromCoord COORD, toCoord COORD) error { +func (h *windowsAnsiEventHandler) clearRect(attributes uint16, fromCoord COORD, toCoord COORD) error { region := SMALL_RECT{Top: fromCoord.Y, Left: fromCoord.X, Bottom: toCoord.Y, Right: toCoord.X} width := toCoord.X - fromCoord.X + 1 height := toCoord.Y - fromCoord.Y + 1 @@ -72,7 +70,7 @@ func (h *WindowsAnsiEventHandler) clearRect(attributes WORD, fromCoord COORD, to buffer := make([]CHAR_INFO, size) - char := CHAR_INFO{WCHAR(FILL_CHARACTER), attributes} + char := CHAR_INFO{ansiterm.FILL_CHARACTER, attributes} for i := 0; i < int(size); i++ { buffer[i] = char } diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go b/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go index ed1998245c07..706d270577e3 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go @@ -3,9 +3,9 @@ package winterm // effectiveSr gets the current effective scroll region in buffer coordinates -func (h *WindowsAnsiEventHandler) effectiveSr(window SMALL_RECT) scrollRegion { - top := AddInRange(window.Top, h.sr.top, window.Top, window.Bottom) - bottom := AddInRange(window.Top, h.sr.bottom, window.Top, window.Bottom) +func (h *windowsAnsiEventHandler) effectiveSr(window SMALL_RECT) scrollRegion { + top := addInRange(window.Top, h.sr.top, window.Top, window.Bottom) + bottom := addInRange(window.Top, h.sr.bottom, window.Top, window.Bottom) if top >= bottom { top = window.Top bottom = window.Bottom @@ -13,7 +13,7 @@ func (h *WindowsAnsiEventHandler) effectiveSr(window SMALL_RECT) scrollRegion { return scrollRegion{top: top, bottom: bottom} } -func (h *WindowsAnsiEventHandler) scrollUp(param int) error { +func (h *windowsAnsiEventHandler) scrollUp(param int) error { info, err := GetConsoleScreenBufferInfo(h.fd) if err != nil { return err @@ -23,11 +23,11 @@ func (h *WindowsAnsiEventHandler) scrollUp(param int) error { return h.scroll(param, sr, info) } -func (h *WindowsAnsiEventHandler) scrollDown(param int) error { +func (h *windowsAnsiEventHandler) scrollDown(param int) error { return h.scrollUp(-param) } -func (h *WindowsAnsiEventHandler) deleteLines(param int) error { +func (h *windowsAnsiEventHandler) deleteLines(param int) error { info, err := GetConsoleScreenBufferInfo(h.fd) if err != nil { return err @@ -44,12 +44,12 @@ func (h *WindowsAnsiEventHandler) deleteLines(param int) error { } } -func (h *WindowsAnsiEventHandler) insertLines(param int) error { +func (h *windowsAnsiEventHandler) insertLines(param int) error { return h.deleteLines(-param) } // scroll scrolls the provided scroll region by param lines. The scroll region is in buffer coordinates. -func (h *WindowsAnsiEventHandler) scroll(param int, sr scrollRegion, info *CONSOLE_SCREEN_BUFFER_INFO) error { +func (h *windowsAnsiEventHandler) scroll(param int, sr scrollRegion, info *CONSOLE_SCREEN_BUFFER_INFO) error { logger.Infof("scroll: scrollTop: %d, scrollBottom: %d", sr.top, sr.bottom) logger.Infof("scroll: windowTop: %d, windowBottom: %d", info.Window.Top, info.Window.Bottom) @@ -64,7 +64,7 @@ func (h *WindowsAnsiEventHandler) scroll(param int, sr scrollRegion, info *CONSO // Origin to which area should be copied destOrigin := COORD{ X: 0, - Y: sr.top - SHORT(param), + Y: sr.top - int16(param), } char := CHAR_INFO{ @@ -78,7 +78,7 @@ func (h *WindowsAnsiEventHandler) scroll(param int, sr scrollRegion, info *CONSO return nil } -func (h *WindowsAnsiEventHandler) deleteCharacters(param int) error { +func (h *windowsAnsiEventHandler) deleteCharacters(param int) error { info, err := GetConsoleScreenBufferInfo(h.fd) if err != nil { return err @@ -86,12 +86,12 @@ func (h *WindowsAnsiEventHandler) deleteCharacters(param int) error { return h.scrollLine(param, info.CursorPosition, info) } -func (h *WindowsAnsiEventHandler) insertCharacters(param int) error { +func (h *windowsAnsiEventHandler) insertCharacters(param int) error { return h.deleteCharacters(-param) } // scrollLine scrolls a line horizontally starting at the provided position by a number of columns. -func (h *WindowsAnsiEventHandler) scrollLine(columns int, position COORD, info *CONSOLE_SCREEN_BUFFER_INFO) error { +func (h *windowsAnsiEventHandler) scrollLine(columns int, position COORD, info *CONSOLE_SCREEN_BUFFER_INFO) error { // Copy from and clip to the scroll region (full buffer width) scrollRect := SMALL_RECT{ Top: position.Y, @@ -102,7 +102,7 @@ func (h *WindowsAnsiEventHandler) scrollLine(columns int, position COORD, info * // Origin to which area should be copied destOrigin := COORD{ - X: position.X - SHORT(columns), + X: position.X - int16(columns), Y: position.Y, } diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go b/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go index 2f963ff132d1..afa7635d77ba 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go @@ -4,6 +4,6 @@ package winterm // AddInRange increments a value by the passed quantity while ensuring the values // always remain within the supplied min / max range. -func AddInRange(n SHORT, increment SHORT, min SHORT, max SHORT) SHORT { +func addInRange(n int16, increment int16, min int16, max int16) int16 { return ensureInRange(n+increment, min, max) } diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go b/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go index 2d492b32e422..4d858ed61118 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go @@ -8,19 +8,19 @@ import ( "os" "strconv" - . "github.com/Azure/go-ansiterm" + "github.com/Azure/go-ansiterm" "github.com/Sirupsen/logrus" ) var logger *logrus.Logger -type WindowsAnsiEventHandler struct { +type windowsAnsiEventHandler struct { fd uintptr file *os.File infoReset *CONSOLE_SCREEN_BUFFER_INFO sr scrollRegion buffer bytes.Buffer - attributes WORD + attributes uint16 inverted bool wrapNext bool drewMarginByte bool @@ -30,10 +30,10 @@ type WindowsAnsiEventHandler struct { curPos COORD } -func CreateWinEventHandler(fd uintptr, file *os.File) AnsiEventHandler { +func CreateWinEventHandler(fd uintptr, file *os.File) ansiterm.AnsiEventHandler { logFile := ioutil.Discard - if isDebugEnv := os.Getenv(LogEnv); isDebugEnv == "1" { + if isDebugEnv := os.Getenv(ansiterm.LogEnv); isDebugEnv == "1" { logFile, _ = os.Create("winEventHandler.log") } @@ -48,7 +48,7 @@ func CreateWinEventHandler(fd uintptr, file *os.File) AnsiEventHandler { return nil } - return &WindowsAnsiEventHandler{ + return &windowsAnsiEventHandler{ fd: fd, file: file, infoReset: infoReset, @@ -57,8 +57,8 @@ func CreateWinEventHandler(fd uintptr, file *os.File) AnsiEventHandler { } type scrollRegion struct { - top SHORT - bottom SHORT + top int16 + bottom int16 } // simulateLF simulates a LF or CR+LF by scrolling if necessary to handle the @@ -68,7 +68,7 @@ type scrollRegion struct { // // In the false case, the caller should ensure that a carriage return // and line feed are inserted or that the text is otherwise wrapped. -func (h *WindowsAnsiEventHandler) simulateLF(includeCR bool) (bool, error) { +func (h *windowsAnsiEventHandler) simulateLF(includeCR bool) (bool, error) { if h.wrapNext { if err := h.Flush(); err != nil { return false, err @@ -89,24 +89,25 @@ func (h *WindowsAnsiEventHandler) simulateLF(includeCR bool) (bool, error) { h.updatePos(pos) } return false, nil - } else { - // A custom scroll region is active. Scroll the window manually to simulate - // the LF. - if err := h.Flush(); err != nil { - return false, err - } - logger.Info("Simulating LF inside scroll region") - if err := h.scrollUp(1); err != nil { + } + + // A custom scroll region is active. Scroll the window manually to simulate + // the LF. + if err := h.Flush(); err != nil { + return false, err + } + logger.Info("Simulating LF inside scroll region") + if err := h.scrollUp(1); err != nil { + return false, err + } + if includeCR { + pos.X = 0 + if err := SetConsoleCursorPosition(h.fd, pos); err != nil { return false, err } - if includeCR { - pos.X = 0 - if err := SetConsoleCursorPosition(h.fd, pos); err != nil { - return false, err - } - } - return true, nil } + return true, nil + } else if pos.Y < info.Window.Bottom { // Let Windows handle the LF. pos.Y++ @@ -133,7 +134,7 @@ func (h *WindowsAnsiEventHandler) simulateLF(includeCR bool) (bool, error) { } // executeLF executes a LF without a CR. -func (h *WindowsAnsiEventHandler) executeLF() error { +func (h *windowsAnsiEventHandler) executeLF() error { handled, err := h.simulateLF(false) if err != nil { return err @@ -145,7 +146,7 @@ func (h *WindowsAnsiEventHandler) executeLF() error { if err != nil { return err } - h.buffer.WriteByte(ANSI_LINE_FEED) + h.buffer.WriteByte(ansiterm.ANSI_LINE_FEED) if pos.X != 0 { if err := h.Flush(); err != nil { return err @@ -159,7 +160,7 @@ func (h *WindowsAnsiEventHandler) executeLF() error { return nil } -func (h *WindowsAnsiEventHandler) Print(b byte) error { +func (h *windowsAnsiEventHandler) Print(b byte) error { if h.wrapNext { h.buffer.WriteByte(h.marginByte) h.clearWrap() @@ -182,9 +183,9 @@ func (h *WindowsAnsiEventHandler) Print(b byte) error { return nil } -func (h *WindowsAnsiEventHandler) Execute(b byte) error { +func (h *windowsAnsiEventHandler) Execute(b byte) error { switch b { - case ANSI_TAB: + case ansiterm.ANSI_TAB: logger.Info("Execute(TAB)") // Move to the next tab stop, but preserve auto-wrap if already set. if !h.wrapNext { @@ -205,11 +206,11 @@ func (h *WindowsAnsiEventHandler) Execute(b byte) error { } return nil - case ANSI_BEL: - h.buffer.WriteByte(ANSI_BEL) + case ansiterm.ANSI_BEL: + h.buffer.WriteByte(ansiterm.ANSI_BEL) return nil - case ANSI_BACKSPACE: + case ansiterm.ANSI_BACKSPACE: if h.wrapNext { if err := h.Flush(); err != nil { return err @@ -223,15 +224,15 @@ func (h *WindowsAnsiEventHandler) Execute(b byte) error { if pos.X > 0 { pos.X-- h.updatePos(pos) - h.buffer.WriteByte(ANSI_BACKSPACE) + h.buffer.WriteByte(ansiterm.ANSI_BACKSPACE) } return nil - case ANSI_VERTICAL_TAB, ANSI_FORM_FEED: + case ansiterm.ANSI_VERTICAL_TAB, ansiterm.ANSI_FORM_FEED: // Treat as true LF. return h.executeLF() - case ANSI_LINE_FEED: + case ansiterm.ANSI_LINE_FEED: // Simulate a CR and LF for now since there is no way in go-ansiterm // to tell if the LF should include CR (and more things break when it's // missing than when it's incorrectly added). @@ -239,9 +240,9 @@ func (h *WindowsAnsiEventHandler) Execute(b byte) error { if handled || err != nil { return err } - return h.buffer.WriteByte(ANSI_LINE_FEED) + return h.buffer.WriteByte(ansiterm.ANSI_LINE_FEED) - case ANSI_CARRIAGE_RETURN: + case ansiterm.ANSI_CARRIAGE_RETURN: if h.wrapNext { if err := h.Flush(); err != nil { return err @@ -255,7 +256,7 @@ func (h *WindowsAnsiEventHandler) Execute(b byte) error { if pos.X != 0 { pos.X = 0 h.updatePos(pos) - h.buffer.WriteByte(ANSI_CARRIAGE_RETURN) + h.buffer.WriteByte(ansiterm.ANSI_CARRIAGE_RETURN) } return nil @@ -264,7 +265,7 @@ func (h *WindowsAnsiEventHandler) Execute(b byte) error { } } -func (h *WindowsAnsiEventHandler) CUU(param int) error { +func (h *windowsAnsiEventHandler) CUU(param int) error { if err := h.Flush(); err != nil { return err } @@ -273,7 +274,7 @@ func (h *WindowsAnsiEventHandler) CUU(param int) error { return h.moveCursorVertical(-param) } -func (h *WindowsAnsiEventHandler) CUD(param int) error { +func (h *windowsAnsiEventHandler) CUD(param int) error { if err := h.Flush(); err != nil { return err } @@ -282,7 +283,7 @@ func (h *WindowsAnsiEventHandler) CUD(param int) error { return h.moveCursorVertical(param) } -func (h *WindowsAnsiEventHandler) CUF(param int) error { +func (h *windowsAnsiEventHandler) CUF(param int) error { if err := h.Flush(); err != nil { return err } @@ -291,7 +292,7 @@ func (h *WindowsAnsiEventHandler) CUF(param int) error { return h.moveCursorHorizontal(param) } -func (h *WindowsAnsiEventHandler) CUB(param int) error { +func (h *windowsAnsiEventHandler) CUB(param int) error { if err := h.Flush(); err != nil { return err } @@ -300,7 +301,7 @@ func (h *WindowsAnsiEventHandler) CUB(param int) error { return h.moveCursorHorizontal(-param) } -func (h *WindowsAnsiEventHandler) CNL(param int) error { +func (h *windowsAnsiEventHandler) CNL(param int) error { if err := h.Flush(); err != nil { return err } @@ -309,7 +310,7 @@ func (h *WindowsAnsiEventHandler) CNL(param int) error { return h.moveCursorLine(param) } -func (h *WindowsAnsiEventHandler) CPL(param int) error { +func (h *windowsAnsiEventHandler) CPL(param int) error { if err := h.Flush(); err != nil { return err } @@ -318,7 +319,7 @@ func (h *WindowsAnsiEventHandler) CPL(param int) error { return h.moveCursorLine(-param) } -func (h *WindowsAnsiEventHandler) CHA(param int) error { +func (h *windowsAnsiEventHandler) CHA(param int) error { if err := h.Flush(); err != nil { return err } @@ -327,7 +328,7 @@ func (h *WindowsAnsiEventHandler) CHA(param int) error { return h.moveCursorColumn(param) } -func (h *WindowsAnsiEventHandler) VPA(param int) error { +func (h *windowsAnsiEventHandler) VPA(param int) error { if err := h.Flush(); err != nil { return err } @@ -339,11 +340,11 @@ func (h *WindowsAnsiEventHandler) VPA(param int) error { } window := h.getCursorWindow(info) position := info.CursorPosition - position.Y = window.Top + SHORT(param) - 1 + position.Y = window.Top + int16(param) - 1 return h.setCursorPosition(position, window) } -func (h *WindowsAnsiEventHandler) CUP(row int, col int) error { +func (h *windowsAnsiEventHandler) CUP(row int, col int) error { if err := h.Flush(); err != nil { return err } @@ -355,11 +356,11 @@ func (h *WindowsAnsiEventHandler) CUP(row int, col int) error { } window := h.getCursorWindow(info) - position := COORD{window.Left + SHORT(col) - 1, window.Top + SHORT(row) - 1} + position := COORD{window.Left + int16(col) - 1, window.Top + int16(row) - 1} return h.setCursorPosition(position, window) } -func (h *WindowsAnsiEventHandler) HVP(row int, col int) error { +func (h *windowsAnsiEventHandler) HVP(row int, col int) error { if err := h.Flush(); err != nil { return err } @@ -368,7 +369,7 @@ func (h *WindowsAnsiEventHandler) HVP(row int, col int) error { return h.CUP(row, col) } -func (h *WindowsAnsiEventHandler) DECTCEM(visible bool) error { +func (h *windowsAnsiEventHandler) DECTCEM(visible bool) error { if err := h.Flush(); err != nil { return err } @@ -377,7 +378,7 @@ func (h *WindowsAnsiEventHandler) DECTCEM(visible bool) error { return nil } -func (h *WindowsAnsiEventHandler) DECOM(enable bool) error { +func (h *windowsAnsiEventHandler) DECOM(enable bool) error { if err := h.Flush(); err != nil { return err } @@ -387,7 +388,7 @@ func (h *WindowsAnsiEventHandler) DECOM(enable bool) error { return h.CUP(1, 1) } -func (h *WindowsAnsiEventHandler) DECCOLM(use132 bool) error { +func (h *windowsAnsiEventHandler) DECCOLM(use132 bool) error { if err := h.Flush(); err != nil { return err } @@ -400,7 +401,7 @@ func (h *WindowsAnsiEventHandler) DECCOLM(use132 bool) error { if err != nil { return err } - targetWidth := SHORT(80) + targetWidth := int16(80) if use132 { targetWidth = 132 } @@ -426,7 +427,7 @@ func (h *WindowsAnsiEventHandler) DECCOLM(use132 bool) error { return SetConsoleCursorPosition(h.fd, COORD{0, 0}) } -func (h *WindowsAnsiEventHandler) ED(param int) error { +func (h *windowsAnsiEventHandler) ED(param int) error { if err := h.Flush(); err != nil { return err } @@ -485,7 +486,7 @@ func (h *WindowsAnsiEventHandler) ED(param int) error { return nil } -func (h *WindowsAnsiEventHandler) EL(param int) error { +func (h *windowsAnsiEventHandler) EL(param int) error { if err := h.Flush(); err != nil { return err } @@ -526,7 +527,7 @@ func (h *WindowsAnsiEventHandler) EL(param int) error { return nil } -func (h *WindowsAnsiEventHandler) IL(param int) error { +func (h *windowsAnsiEventHandler) IL(param int) error { if err := h.Flush(); err != nil { return err } @@ -535,7 +536,7 @@ func (h *WindowsAnsiEventHandler) IL(param int) error { return h.insertLines(param) } -func (h *WindowsAnsiEventHandler) DL(param int) error { +func (h *windowsAnsiEventHandler) DL(param int) error { if err := h.Flush(); err != nil { return err } @@ -544,7 +545,7 @@ func (h *WindowsAnsiEventHandler) DL(param int) error { return h.deleteLines(param) } -func (h *WindowsAnsiEventHandler) ICH(param int) error { +func (h *windowsAnsiEventHandler) ICH(param int) error { if err := h.Flush(); err != nil { return err } @@ -553,7 +554,7 @@ func (h *WindowsAnsiEventHandler) ICH(param int) error { return h.insertCharacters(param) } -func (h *WindowsAnsiEventHandler) DCH(param int) error { +func (h *windowsAnsiEventHandler) DCH(param int) error { if err := h.Flush(); err != nil { return err } @@ -562,7 +563,7 @@ func (h *WindowsAnsiEventHandler) DCH(param int) error { return h.deleteCharacters(param) } -func (h *WindowsAnsiEventHandler) SGR(params []int) error { +func (h *windowsAnsiEventHandler) SGR(params []int) error { if err := h.Flush(); err != nil { return err } @@ -579,13 +580,13 @@ func (h *WindowsAnsiEventHandler) SGR(params []int) error { } else { for _, attr := range params { - if attr == ANSI_SGR_RESET { + if attr == ansiterm.ANSI_SGR_RESET { h.attributes = h.infoReset.Attributes h.inverted = false continue } - h.attributes, h.inverted = collectAnsiIntoWindowsAttributes(h.attributes, h.inverted, h.infoReset.Attributes, SHORT(attr)) + h.attributes, h.inverted = collectAnsiIntoWindowsAttributes(h.attributes, h.inverted, h.infoReset.Attributes, int16(attr)) } } @@ -601,7 +602,7 @@ func (h *WindowsAnsiEventHandler) SGR(params []int) error { return nil } -func (h *WindowsAnsiEventHandler) SU(param int) error { +func (h *windowsAnsiEventHandler) SU(param int) error { if err := h.Flush(); err != nil { return err } @@ -610,7 +611,7 @@ func (h *WindowsAnsiEventHandler) SU(param int) error { return h.scrollUp(param) } -func (h *WindowsAnsiEventHandler) SD(param int) error { +func (h *windowsAnsiEventHandler) SD(param int) error { if err := h.Flush(); err != nil { return err } @@ -619,29 +620,29 @@ func (h *WindowsAnsiEventHandler) SD(param int) error { return h.scrollDown(param) } -func (h *WindowsAnsiEventHandler) DA(params []string) error { +func (h *windowsAnsiEventHandler) DA(params []string) error { logger.Infof("DA: [%v]", params) // DA cannot be implemented because it must send data on the VT100 input stream, // which is not available to go-ansiterm. return nil } -func (h *WindowsAnsiEventHandler) DECSTBM(top int, bottom int) error { +func (h *windowsAnsiEventHandler) DECSTBM(top int, bottom int) error { if err := h.Flush(); err != nil { return err } logger.Infof("DECSTBM: [%d, %d]", top, bottom) // Windows is 0 indexed, Linux is 1 indexed - h.sr.top = SHORT(top - 1) - h.sr.bottom = SHORT(bottom - 1) + h.sr.top = int16(top - 1) + h.sr.bottom = int16(bottom - 1) // This command also moves the cursor to the origin. h.clearWrap() return h.CUP(1, 1) } -func (h *WindowsAnsiEventHandler) RI() error { +func (h *windowsAnsiEventHandler) RI() error { if err := h.Flush(); err != nil { return err } @@ -656,17 +657,17 @@ func (h *WindowsAnsiEventHandler) RI() error { sr := h.effectiveSr(info.Window) if info.CursorPosition.Y == sr.top { return h.scrollDown(1) - } else { - return h.moveCursorVertical(-1) } + + return h.moveCursorVertical(-1) } -func (h *WindowsAnsiEventHandler) IND() error { +func (h *windowsAnsiEventHandler) IND() error { logger.Info("IND: []") return h.executeLF() } -func (h *WindowsAnsiEventHandler) Flush() error { +func (h *windowsAnsiEventHandler) Flush() error { h.curInfo = nil if h.buffer.Len() > 0 { logger.Infof("Flush: [%s]", h.buffer.Bytes()) @@ -683,7 +684,7 @@ func (h *WindowsAnsiEventHandler) Flush() error { return err } - charInfo := []CHAR_INFO{{UnicodeChar: WCHAR(h.marginByte), Attributes: info.Attributes}} + charInfo := []CHAR_INFO{{UnicodeChar: uint16(h.marginByte), Attributes: info.Attributes}} size := COORD{1, 1} position := COORD{0, 0} region := SMALL_RECT{Left: info.CursorPosition.X, Top: info.CursorPosition.Y, Right: info.CursorPosition.X, Bottom: info.CursorPosition.Y} @@ -697,7 +698,7 @@ func (h *WindowsAnsiEventHandler) Flush() error { // cacheConsoleInfo ensures that the current console screen information has been queried // since the last call to Flush(). It must be called before accessing h.curInfo or h.curPos. -func (h *WindowsAnsiEventHandler) getCurrentInfo() (COORD, *CONSOLE_SCREEN_BUFFER_INFO, error) { +func (h *windowsAnsiEventHandler) getCurrentInfo() (COORD, *CONSOLE_SCREEN_BUFFER_INFO, error) { if h.curInfo == nil { info, err := GetConsoleScreenBufferInfo(h.fd) if err != nil { @@ -709,7 +710,7 @@ func (h *WindowsAnsiEventHandler) getCurrentInfo() (COORD, *CONSOLE_SCREEN_BUFFE return h.curPos, h.curInfo, nil } -func (h *WindowsAnsiEventHandler) updatePos(pos COORD) { +func (h *windowsAnsiEventHandler) updatePos(pos COORD) { if h.curInfo == nil { panic("failed to call getCurrentInfo before calling updatePos") } @@ -719,7 +720,7 @@ func (h *WindowsAnsiEventHandler) updatePos(pos COORD) { // clearWrap clears the state where the cursor is in the margin // waiting for the next character before wrapping the line. This must // be done before most operations that act on the cursor. -func (h *WindowsAnsiEventHandler) clearWrap() { +func (h *windowsAnsiEventHandler) clearWrap() { h.wrapNext = false h.drewMarginByte = false } diff --git a/vendor/github.com/Azure/go-autorest/autorest/BUILD b/vendor/github.com/Azure/go-autorest/autorest/BUILD index f9fed41b0892..820faee9823b 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/BUILD +++ b/vendor/github.com/Azure/go-autorest/autorest/BUILD @@ -10,6 +10,7 @@ load( go_library( name = "go_default_library", srcs = [ + "authorization.go", "autorest.go", "client.go", "error.go", @@ -20,6 +21,7 @@ go_library( "version.go", ], tags = ["automanaged"], + deps = ["//vendor/github.com/Azure/go-autorest/autorest/adal:go_default_library"], ) filegroup( @@ -33,6 +35,7 @@ filegroup( name = "all-srcs", srcs = [ ":package-srcs", + "//vendor/github.com/Azure/go-autorest/autorest/adal:all-srcs", "//vendor/github.com/Azure/go-autorest/autorest/azure:all-srcs", "//vendor/github.com/Azure/go-autorest/autorest/date:all-srcs", "//vendor/github.com/Azure/go-autorest/autorest/to:all-srcs", diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/BUILD b/vendor/github.com/Azure/go-autorest/autorest/adal/BUILD new file mode 100644 index 000000000000..b1cdac65efdc --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/adal/BUILD @@ -0,0 +1,34 @@ +package(default_visibility = ["//visibility:public"]) + +licenses(["notice"]) + +load( + "@io_bazel_rules_go//go:def.bzl", + "go_library", +) + +go_library( + name = "go_default_library", + srcs = [ + "config.go", + "devicetoken.go", + "persist.go", + "sender.go", + "token.go", + ], + tags = ["automanaged"], + deps = ["//vendor/github.com/dgrijalva/jwt-go:go_default_library"], +) + +filegroup( + name = "package-srcs", + srcs = glob(["**"]), + tags = ["automanaged"], + visibility = ["//visibility:private"], +) + +filegroup( + name = "all-srcs", + srcs = [":package-srcs"], + tags = ["automanaged"], +) diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/README.md b/vendor/github.com/Azure/go-autorest/autorest/adal/README.md new file mode 100644 index 000000000000..a17cf98c6215 --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/adal/README.md @@ -0,0 +1,253 @@ +# Azure Active Directory library for Go + +This project provides a stand alone Azure Active Directory library for Go. The code was extracted +from [go-autorest](https://github.com/Azure/go-autorest/) project, which is used as a base for +[azure-sdk-for-go](https://github.com/Azure/azure-sdk-for-go). + + +## Installation + +``` +go get -u github.com/Azure/go-autorest/autorest/adal +``` + +## Usage + +An Active Directory application is required in order to use this library. An application can be registered in the [Azure Portal](https://portal.azure.com/) follow these [guidelines](https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-integrating-applications) or using the [Azure CLI](https://github.com/Azure/azure-cli). + +### Register an Azure AD Application with secret + + +1. Register a new application with a `secret` credential + + ``` + az ad app create \ + --display-name example-app \ + --homepage https://example-app/home \ + --identifier-uris https://example-app/app \ + --password secret + ``` + +2. Create a service principal using the `Application ID` from previous step + + ``` + az ad sp create --id "Application ID" + ``` + + * Replace `Application ID` with `appId` from step 1. + +### Register an Azure AD Application with certificate + +1. Create a private key + + ``` + openssl genrsa -out "example-app.key" 2048 + ``` + +2. Create the certificate + + ``` + openssl req -new -key "example-app.key" -subj "/CN=example-app" -out "example-app.csr" + openssl x509 -req -in "example-app.csr" -signkey "example-app.key" -out "example-app.crt" -days 10000 + ``` + +3. Create the PKCS12 version of the certificate containing also the private key + + ``` + openssl pkcs12 -export -out "example-app.pfx" -inkey "example-app.key" -in "example-app.crt" -passout pass: + + ``` + +4. Register a new application with the certificate content form `example-app.crt` + + ``` + certificateContents="$(tail -n+2 "example-app.crt" | head -n-1)" + + az ad app create \ + --display-name example-app \ + --homepage https://example-app/home \ + --identifier-uris https://example-app/app \ + --key-usage Verify --end-date 2018-01-01 \ + --key-value "${certificateContents}" + ``` + +5. Create a service principal using the `Application ID` from previous step + + ``` + az ad sp create --id "APPLICATION_ID" + ``` + + * Replace `APPLICATION_ID` with `appId` from step 4. + + +### Grant the necessary permissions + +Azure relies on a Role-Based Access Control (RBAC) model to manage the access to resources at a fine-grained +level. There is a set of [pre-defined roles](https://docs.microsoft.com/en-us/azure/active-directory/role-based-access-built-in-roles) +which can be assigned to a service principal of an Azure AD application depending of your needs. + +``` +az role assignment create --assigner "SERVICE_PRINCIPAL_ID" --role "ROLE_NAME" +``` + +* Replace the `SERVICE_PRINCIPAL_ID` with the `appId` from previous step. +* Replace the `ROLE_NAME` with a role name of your choice. + +It is also possible to define custom role definitions. + +``` +az role definition create --role-definition role-definition.json +``` + +* Check [custom roles](https://docs.microsoft.com/en-us/azure/active-directory/role-based-access-control-custom-roles) for more details regarding the content of `role-definition.json` file. + + +### Acquire Access Token + +The common configuration used by all flows: + +```Go +const activeDirectoryEndpoint = "https://login.microsoftonline.com/" +tenantID := "TENANT_ID" +oauthConfig, err := adal.NewOAuthConfig(activeDirectoryEndpoint, tenantID) + +applicationID := "APPLICATION_ID" + +callback := func(token adal.Token) error { + // This is called after the token is acquired +} + +// The resource for which the token is acquired +resource := "https://management.core.windows.net/" +``` + +* Replace the `TENANT_ID` with your tenant ID. +* Replace the `APPLICATION_ID` with the value from previous section. + +#### Client Credentials + +```Go +applicationSecret := "APPLICATION_SECRET" + +spt, err := adal.NewServicePrincipalToken( + oauthConfig, + appliationID, + applicationSecret, + resource, + callbacks...) +if err != nil { + return nil, err +} + +// Acquire a new access token +err = spt.Refresh() +if (err == nil) { + token := spt.Token +} +``` + +* Replace the `APPLICATION_SECRET` with the `password` value from previous section. + +#### Client Certificate + +```Go +certificatePath := "./example-app.pfx" + +certData, err := ioutil.ReadFile(certificatePath) +if err != nil { + return nil, fmt.Errorf("failed to read the certificate file (%s): %v", certificatePath, err) +} + +// Get the certificate and private key from pfx file +certificate, rsaPrivateKey, err := decodePkcs12(certData, "") +if err != nil { + return nil, fmt.Errorf("failed to decode pkcs12 certificate while creating spt: %v", err) +} + +spt, err := adal.NewServicePrincipalTokenFromCertificate( + oauthConfig, + applicationID, + certificate, + rsaPrivateKey, + resource, + callbacks...) + +// Acquire a new access token +err = spt.Refresh() +if (err == nil) { + token := spt.Token +} +``` + +* Update the certificate path to point to the example-app.pfx file which was created in previous section. + + +#### Device Code + +```Go +oauthClient := &http.Client{} + +// Acquire the device code +deviceCode, err := adal.InitiateDeviceAuth( + oauthClient, + oauthConfig, + applicationID, + resource) +if err != nil { + return nil, fmt.Errorf("Failed to start device auth flow: %s", err) +} + +// Display the authentication message +fmt.Println(*deviceCode.Message) + +// Wait here until the user is authenticated +token, err := adal.WaitForUserCompletion(oauthClient, deviceCode) +if err != nil { + return nil, fmt.Errorf("Failed to finish device auth flow: %s", err) +} + +spt, err := adal.NewServicePrincipalTokenFromManualToken( + oauthConfig, + applicationID, + resource, + *token, + callbacks...) + +if (err == nil) { + token := spt.Token +} +``` + +### Command Line Tool + +A command line tool is available in `cmd/adal.go` that can acquire a token for a given resource. It supports all flows mentioned above. + +``` +adal -h + +Usage of ./adal: + -applicationId string + application id + -certificatePath string + path to pk12/PFC application certificate + -mode string + authentication mode (device, secret, cert, refresh) (default "device") + -resource string + resource for which the token is requested + -secret string + application secret + -tenantId string + tenant id + -tokenCachePath string + location of oath token cache (default "/home/cgc/.adal/accessToken.json") +``` + +Example acquire a token for `https://management.core.windows.net/` using device code flow: + +``` +adal -mode device \ + -applicationId "APPLICATION_ID" \ + -tenantId "TENANT_ID" \ + -resource https://management.core.windows.net/ + +``` diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/config.go b/vendor/github.com/Azure/go-autorest/autorest/adal/config.go new file mode 100644 index 000000000000..12375e0e4bb8 --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/adal/config.go @@ -0,0 +1,51 @@ +package adal + +import ( + "fmt" + "net/url" +) + +const ( + activeDirectoryAPIVersion = "1.0" +) + +// OAuthConfig represents the endpoints needed +// in OAuth operations +type OAuthConfig struct { + AuthorityEndpoint url.URL + AuthorizeEndpoint url.URL + TokenEndpoint url.URL + DeviceCodeEndpoint url.URL +} + +// NewOAuthConfig returns an OAuthConfig with tenant specific urls +func NewOAuthConfig(activeDirectoryEndpoint, tenantID string) (*OAuthConfig, error) { + const activeDirectoryEndpointTemplate = "%s/oauth2/%s?api-version=%s" + u, err := url.Parse(activeDirectoryEndpoint) + if err != nil { + return nil, err + } + authorityURL, err := u.Parse(tenantID) + if err != nil { + return nil, err + } + authorizeURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "authorize", activeDirectoryAPIVersion)) + if err != nil { + return nil, err + } + tokenURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "token", activeDirectoryAPIVersion)) + if err != nil { + return nil, err + } + deviceCodeURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "devicecode", activeDirectoryAPIVersion)) + if err != nil { + return nil, err + } + + return &OAuthConfig{ + AuthorityEndpoint: *authorityURL, + AuthorizeEndpoint: *authorizeURL, + TokenEndpoint: *tokenURL, + DeviceCodeEndpoint: *deviceCodeURL, + }, nil +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/devicetoken.go b/vendor/github.com/Azure/go-autorest/autorest/adal/devicetoken.go similarity index 64% rename from vendor/github.com/Azure/go-autorest/autorest/azure/devicetoken.go rename to vendor/github.com/Azure/go-autorest/autorest/adal/devicetoken.go index e1d5498a80f1..6c511f8c8779 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/devicetoken.go +++ b/vendor/github.com/Azure/go-autorest/autorest/adal/devicetoken.go @@ -1,4 +1,4 @@ -package azure +package adal /* This file is largely based on rjw57/oauth2device's code, with the follow differences: @@ -10,16 +10,17 @@ package azure */ import ( + "encoding/json" "fmt" + "io/ioutil" "net/http" "net/url" + "strings" "time" - - "github.com/Azure/go-autorest/autorest" ) const ( - logPrefix = "autorest/azure/devicetoken:" + logPrefix = "autorest/adal/devicetoken:" ) var ( @@ -38,10 +39,17 @@ var ( // 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) + // ErrDeviceCodeEmpty represents an empty device code from the device endpoint while using device flow + ErrDeviceCodeEmpty = fmt.Errorf("%s Error while retrieving device code: Device Code Empty", logPrefix) + + // ErrOAuthTokenEmpty represents an empty OAuth token from the token endpoint when using device flow + ErrOAuthTokenEmpty = fmt.Errorf("%s Error while retrieving OAuth token: Token Empty", 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)" + errStatusNotOK = "Error HTTP status != 200" ) // DeviceCode is the object returned by the device auth endpoint @@ -79,31 +87,45 @@ type deviceToken struct { // 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) +func InitiateDeviceAuth(sender Sender, oauthConfig OAuthConfig, clientID, resource string) (*DeviceCode, error) { + v := url.Values{ + "client_id": []string{clientID}, + "resource": []string{resource}, + } + + s := v.Encode() + body := ioutil.NopCloser(strings.NewReader(s)) + + req, err := http.NewRequest(http.MethodPost, oauthConfig.DeviceCodeEndpoint.String(), body) + if err != nil { + return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeSendingFails, err.Error()) + } + + req.ContentLength = int64(len(s)) + req.Header.Set(contentType, mimeTypeFormPost) + resp, err := sender.Do(req) if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeSendingFails, err) + return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeSendingFails, err.Error()) + } + defer resp.Body.Close() + + rb, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, err.Error()) + } + + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, errStatusNotOK) + } + + if len(strings.Trim(string(rb), " ")) == 0 { + return nil, ErrDeviceCodeEmpty } var code DeviceCode - err = autorest.Respond( - resp, - autorest.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&code), - autorest.ByClosing()) + err = json.Unmarshal(rb, &code) if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, err) + return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, err.Error()) } code.ClientID = clientID @@ -115,33 +137,46 @@ func InitiateDeviceAuth(client *autorest.Client, oauthConfig OAuthConfig, client // 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) +func CheckForUserCompletion(sender Sender, code *DeviceCode) (*Token, error) { + v := url.Values{ + "client_id": []string{code.ClientID}, + "code": []string{*code.DeviceCode}, + "grant_type": []string{OAuthGrantTypeDeviceCode}, + "resource": []string{code.Resource}, + } + + s := v.Encode() + body := ioutil.NopCloser(strings.NewReader(s)) + + req, err := http.NewRequest(http.MethodPost, code.OAuthConfig.TokenEndpoint.String(), body) + if err != nil { + return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenSendingFails, err.Error()) + } + + req.ContentLength = int64(len(s)) + req.Header.Set(contentType, mimeTypeFormPost) + resp, err := sender.Do(req) + if err != nil { + return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenSendingFails, err.Error()) + } + defer resp.Body.Close() + + rb, err := ioutil.ReadAll(resp.Body) if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenSendingFails, err) + return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenHandlingFails, err.Error()) + } + + if resp.StatusCode != http.StatusOK && len(strings.Trim(string(rb), " ")) == 0 { + return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenHandlingFails, errStatusNotOK) + } + if len(strings.Trim(string(rb), " ")) == 0 { + return nil, ErrOAuthTokenEmpty } var token deviceToken - err = autorest.Respond( - resp, - autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusBadRequest), - autorest.ByUnmarshallingJSON(&token), - autorest.ByClosing()) + err = json.Unmarshal(rb, &token) if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenHandlingFails, err) + return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenHandlingFails, err.Error()) } if token.Error == nil { @@ -164,12 +199,12 @@ func CheckForUserCompletion(client *autorest.Client, code *DeviceCode) (*Token, // 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) { +func WaitForUserCompletion(sender Sender, code *DeviceCode) (*Token, error) { intervalDuration := time.Duration(*code.Interval) * time.Second waitDuration := intervalDuration for { - token, err := CheckForUserCompletion(client, code) + token, err := CheckForUserCompletion(sender, code) if err == nil { return token, nil diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/persist.go b/vendor/github.com/Azure/go-autorest/autorest/adal/persist.go similarity index 99% rename from vendor/github.com/Azure/go-autorest/autorest/azure/persist.go rename to vendor/github.com/Azure/go-autorest/autorest/adal/persist.go index d5cf62ddc7ba..73711c6674ea 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/persist.go +++ b/vendor/github.com/Azure/go-autorest/autorest/adal/persist.go @@ -1,4 +1,4 @@ -package azure +package adal import ( "encoding/json" diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/sender.go b/vendor/github.com/Azure/go-autorest/autorest/adal/sender.go new file mode 100644 index 000000000000..7928c971abbe --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/adal/sender.go @@ -0,0 +1,46 @@ +package adal + +import ( + "net/http" +) + +const ( + contentType = "Content-Type" + mimeTypeFormPost = "application/x-www-form-urlencoded" +) + +// Sender is the interface that wraps the Do method to send HTTP requests. +// +// The standard http.Client conforms to this interface. +type Sender interface { + Do(*http.Request) (*http.Response, error) +} + +// SenderFunc is a method that implements the Sender interface. +type SenderFunc func(*http.Request) (*http.Response, error) + +// Do implements the Sender interface on SenderFunc. +func (sf SenderFunc) Do(r *http.Request) (*http.Response, error) { + return sf(r) +} + +// SendDecorator takes and possibily decorates, by wrapping, a Sender. Decorators may affect the +// http.Request and pass it along or, first, pass the http.Request along then react to the +// http.Response result. +type SendDecorator func(Sender) Sender + +// CreateSender creates, decorates, and returns, as a Sender, the default http.Client. +func CreateSender(decorators ...SendDecorator) Sender { + return DecorateSender(&http.Client{}, decorators...) +} + +// DecorateSender accepts a Sender and a, possibly empty, set of SendDecorators, which is applies to +// the Sender. Decorators are applied in the order received, but their affect upon the request +// depends on whether they are a pre-decorator (change the http.Request and then pass it along) or a +// post-decorator (pass the http.Request along and react to the results in http.Response). +func DecorateSender(s Sender, decorators ...SendDecorator) Sender { + for _, decorate := range decorators { + s = decorate(s) + } + return s +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/token.go b/vendor/github.com/Azure/go-autorest/autorest/adal/token.go similarity index 69% rename from vendor/github.com/Azure/go-autorest/autorest/azure/token.go rename to vendor/github.com/Azure/go-autorest/autorest/adal/token.go index cfcd030114c6..559fc6653583 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/token.go +++ b/vendor/github.com/Azure/go-autorest/autorest/adal/token.go @@ -1,4 +1,4 @@ -package azure +package adal import ( "crypto/rand" @@ -6,13 +6,15 @@ import ( "crypto/sha1" "crypto/x509" "encoding/base64" + "encoding/json" "fmt" + "io/ioutil" "net/http" "net/url" "strconv" + "strings" "time" - "github.com/Azure/go-autorest/autorest" "github.com/dgrijalva/jwt-go" ) @@ -28,6 +30,9 @@ const ( // OAuthGrantTypeRefreshToken is the "grant_type" identifier used in refresh token flows OAuthGrantTypeRefreshToken = "refresh_token" + + // managedIdentitySettingsPath is the path to the MSI Extension settings file (to discover the endpoint) + managedIdentitySettingsPath = "/var/lib/waagent/ManagedIdentity-Settings" ) var expirationBase time.Time @@ -36,6 +41,18 @@ func init() { expirationBase, _ = time.Parse(time.RFC3339, tokenBaseDate) } +// OAuthTokenProvider is an interface which should be implemented by an access token retriever +type OAuthTokenProvider interface { + OAuthToken() string +} + +// Refresher is an interface for token refresh functionality +type Refresher interface { + Refresh() error + RefreshExchange(resource string) error + EnsureFresh() error +} + // TokenRefreshCallback is the type representing callbacks that will be called after // a successful token refresh type TokenRefreshCallback func(Token) error @@ -73,14 +90,9 @@ func (t Token) WillExpireIn(d time.Duration) bool { return !t.Expires().After(time.Now().Add(d)) } -// WithAuthorization returns a PrepareDecorator that adds an HTTP Authorization header whose -// value is "Bearer " followed by the AccessToken of the Token. -func (t *Token) WithAuthorization() autorest.PrepareDecorator { - return func(p autorest.Preparer) autorest.Preparer { - return autorest.PreparerFunc(func(r *http.Request) (*http.Request, error) { - return (autorest.WithBearerAuthorization(t.AccessToken)(p)).Prepare(r) - }) - } +//OAuthToken return the current access token +func (t *Token) OAuthToken() string { + return t.AccessToken } // ServicePrincipalNoSecret represents a secret type that contains no secret @@ -118,6 +130,17 @@ type ServicePrincipalCertificateSecret struct { PrivateKey *rsa.PrivateKey } +// ServicePrincipalMSISecret implements ServicePrincipalSecret for machines running the MSI Extension. +type ServicePrincipalMSISecret struct { +} + +// SetAuthenticationValues is a method of the interface ServicePrincipalSecret. +// MSI extension requires the authority field to be set to the real tenant authority endpoint +func (msiSecret *ServicePrincipalMSISecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { + v.Set("authority", spt.oauthConfig.AuthorityEndpoint.String()) + return nil +} + // SignJwt returns the JWT signed with the certificate's private key. func (secret *ServicePrincipalCertificateSecret) SignJwt(spt *ServicePrincipalToken) (string, error) { hasher := sha1.New() @@ -173,7 +196,7 @@ type ServicePrincipalToken struct { resource string autoRefresh bool refreshWithin time.Duration - sender autorest.Sender + sender Sender refreshCallbacks []TokenRefreshCallback } @@ -238,10 +261,56 @@ func NewServicePrincipalTokenFromCertificate(oauthConfig OAuthConfig, clientID s ) } +// NewServicePrincipalTokenFromMSI creates a ServicePrincipalToken via the MSI VM Extension. +func NewServicePrincipalTokenFromMSI(oauthConfig OAuthConfig, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { + return newServicePrincipalTokenFromMSI(oauthConfig, resource, managedIdentitySettingsPath, callbacks...) +} + +func newServicePrincipalTokenFromMSI(oauthConfig OAuthConfig, resource, settingsPath string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { + // Read MSI settings + bytes, err := ioutil.ReadFile(settingsPath) + if err != nil { + return nil, err + } + msiSettings := struct { + URL string `json:"url"` + }{} + err = json.Unmarshal(bytes, &msiSettings) + if err != nil { + return nil, err + } + + // We set the oauth config token endpoint to be MSI's endpoint + // We leave the authority as-is so MSI can POST it with the token request + msiEndpointURL, err := url.Parse(msiSettings.URL) + if err != nil { + return nil, err + } + + msiTokenEndpointURL, err := msiEndpointURL.Parse("/oauth2/token") + if err != nil { + return nil, err + } + + oauthConfig.TokenEndpoint = *msiTokenEndpointURL + + spt := &ServicePrincipalToken{ + oauthConfig: oauthConfig, + secret: &ServicePrincipalMSISecret{}, + resource: resource, + autoRefresh: true, + refreshWithin: defaultRefresh, + sender: &http.Client{}, + refreshCallbacks: callbacks, + } + + return spt, nil +} + // EnsureFresh will refresh the token if it will expire within the refresh window (as set by -// RefreshWithin). +// RefreshWithin) and autoRefresh flag is on. func (spt *ServicePrincipalToken) EnsureFresh() error { - if spt.WillExpireIn(spt.refreshWithin) { + if spt.autoRefresh && spt.WillExpireIn(spt.refreshWithin) { return spt.Refresh() } return nil @@ -253,8 +322,7 @@ func (spt *ServicePrincipalToken) InvokeRefreshCallbacks(token Token) error { 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 fmt.Errorf("adal: TokenRefreshCallback handler failed. Error = '%v'", err) } } } @@ -287,39 +355,40 @@ func (spt *ServicePrincipalToken) refreshInternal(resource string) error { } } - req, _ := autorest.Prepare(&http.Request{}, - autorest.AsPost(), - autorest.AsFormURLEncoded(), - autorest.WithBaseURL(spt.oauthConfig.TokenEndpoint.String()), - autorest.WithFormData(v)) - - resp, err := autorest.SendWithSender(spt.sender, req) + s := v.Encode() + body := ioutil.NopCloser(strings.NewReader(s)) + req, err := http.NewRequest(http.MethodPost, spt.oauthConfig.TokenEndpoint.String(), body) if err != nil { - return autorest.NewErrorWithError(err, - "azure.ServicePrincipalToken", "Refresh", resp, "Failure sending request for Service Principal %s", - spt.clientID) + return fmt.Errorf("adal: Failed to build the refresh request. Error = '%v'", err) } - var newToken Token - err = autorest.Respond(resp, - autorest.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&newToken), - autorest.ByClosing()) + req.ContentLength = int64(len(s)) + req.Header.Set(contentType, mimeTypeFormPost) + resp, err := spt.sender.Do(req) if err != nil { - return autorest.NewErrorWithError(err, - "azure.ServicePrincipalToken", "Refresh", resp, "Failure handling response to Service Principal %s request", - spt.clientID) + return fmt.Errorf("adal: Failed to execute the refresh request. Error = '%v'", err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("adal: Refresh request failed. Status Code = '%d'", resp.StatusCode) } - spt.Token = newToken - - err = spt.InvokeRefreshCallbacks(newToken) + rb, err := ioutil.ReadAll(resp.Body) if err != nil { - // its already wrapped inside InvokeRefreshCallbacks - return err + return fmt.Errorf("adal: Failed to read a new service principal token during refresh. Error = '%v'", err) + } + if len(strings.Trim(string(rb), " ")) == 0 { + return fmt.Errorf("adal: Empty service principal token received during refresh") + } + var token Token + err = json.Unmarshal(rb, &token) + if err != nil { + return fmt.Errorf("adal: Failed to unmarshal the service principal token during refresh. Error = '%v' JSON = '%s'", err, string(rb)) } - return nil + spt.Token = token + + return spt.InvokeRefreshCallbacks(token) } // SetAutoRefresh enables or disables automatic refreshing of stale tokens. @@ -334,30 +403,6 @@ func (spt *ServicePrincipalToken) SetRefreshWithin(d time.Duration) { return } -// SetSender sets the autorest.Sender used when obtaining the Service Principal token. An +// SetSender sets the http.Client used when obtaining the Service Principal token. An // undecorated http.Client is used by default. -func (spt *ServicePrincipalToken) SetSender(s autorest.Sender) { - spt.sender = s -} - -// WithAuthorization returns a PrepareDecorator that adds an HTTP Authorization header whose -// value is "Bearer " followed by the AccessToken of the ServicePrincipalToken. -// -// By default, the token will automatically refresh if nearly expired (as determined by the -// RefreshWithin interval). Use the AutoRefresh method to enable or disable automatically refreshing -// tokens. -func (spt *ServicePrincipalToken) WithAuthorization() autorest.PrepareDecorator { - return func(p autorest.Preparer) autorest.Preparer { - return autorest.PreparerFunc(func(r *http.Request) (*http.Request, error) { - if spt.autoRefresh { - err := spt.EnsureFresh() - if err != nil { - return r, autorest.NewErrorWithError(err, - "azure.ServicePrincipalToken", "WithAuthorization", nil, "Failed to refresh Service Principal Token for request to %s", - r.URL) - } - } - return (autorest.WithBearerAuthorization(spt.AccessToken)(p)).Prepare(r) - }) - } -} +func (spt *ServicePrincipalToken) SetSender(s Sender) { spt.sender = s } diff --git a/vendor/github.com/Azure/go-autorest/autorest/authorization.go b/vendor/github.com/Azure/go-autorest/autorest/authorization.go new file mode 100644 index 000000000000..7f4e3d84540e --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/authorization.go @@ -0,0 +1,57 @@ +package autorest + +import ( + "fmt" + "net/http" + + "github.com/Azure/go-autorest/autorest/adal" +) + +// Authorizer is the interface that provides a PrepareDecorator used to supply request +// authorization. Most often, the Authorizer decorator runs last so it has access to the full +// state of the formed HTTP request. +type Authorizer interface { + WithAuthorization() PrepareDecorator +} + +// NullAuthorizer implements a default, "do nothing" Authorizer. +type NullAuthorizer struct{} + +// WithAuthorization returns a PrepareDecorator that does nothing. +func (na NullAuthorizer) WithAuthorization() PrepareDecorator { + return WithNothing() +} + +// BearerAuthorizer implements the bearer authorization +type BearerAuthorizer struct { + tokenProvider adal.OAuthTokenProvider +} + +// NewBearerAuthorizer crates a BearerAuthorizer using the given token provider +func NewBearerAuthorizer(tp adal.OAuthTokenProvider) *BearerAuthorizer { + return &BearerAuthorizer{tokenProvider: tp} +} + +func (ba *BearerAuthorizer) withBearerAuthorization() PrepareDecorator { + return WithHeader(headerAuthorization, fmt.Sprintf("Bearer %s", ba.tokenProvider.OAuthToken())) +} + +// WithAuthorization returns a PrepareDecorator that adds an HTTP Authorization header whose +// value is "Bearer " followed by the token. +// +// By default, the token will be automatically refreshed through the Refresher interface. +func (ba *BearerAuthorizer) WithAuthorization() PrepareDecorator { + return func(p Preparer) Preparer { + return PreparerFunc(func(r *http.Request) (*http.Request, error) { + refresher, ok := ba.tokenProvider.(adal.Refresher) + if ok { + err := refresher.EnsureFresh() + if err != nil { + return r, NewErrorWithError(err, "azure.BearerAuthorizer", "WithAuthorization", nil, + "Failed to refresh the Token for request to %s", r.URL) + } + } + return (ba.withBearerAuthorization()(p)).Prepare(r) + }) + } +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/autorest.go b/vendor/github.com/Azure/go-autorest/autorest/autorest.go index 9804f401ef9f..51f1c4bbcac2 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/autorest.go +++ b/vendor/github.com/Azure/go-autorest/autorest/autorest.go @@ -16,6 +16,7 @@ and Responding. A typical pattern is: DoRetryForAttempts(5, time.Second)) err = Respond(resp, + ByDiscardingBody(), ByClosing()) Each phase relies on decorators to modify and / or manage processing. Decorators may first modify diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/BUILD b/vendor/github.com/Azure/go-autorest/autorest/azure/BUILD index bd8705000eac..ec59a5791477 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/BUILD +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/BUILD @@ -12,17 +12,12 @@ go_library( srcs = [ "async.go", "azure.go", - "config.go", - "devicetoken.go", "environments.go", - "persist.go", - "token.go", ], tags = ["automanaged"], deps = [ "//vendor/github.com/Azure/go-autorest/autorest:go_default_library", "//vendor/github.com/Azure/go-autorest/autorest/date:go_default_library", - "//vendor/github.com/dgrijalva/jwt-go:go_default_library", ], ) diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/async.go b/vendor/github.com/Azure/go-autorest/autorest/azure/async.go index 280d32a61dde..332a8909d1a9 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/async.go +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/async.go @@ -3,12 +3,13 @@ package azure import ( "bytes" "fmt" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/date" "io/ioutil" "net/http" "strings" "time" + + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/date" ) const ( @@ -16,12 +17,6 @@ const ( ) const ( - methodDelete = "DELETE" - methodPatch = "PATCH" - methodPost = "POST" - methodPut = "PUT" - methodGet = "GET" - operationInProgress string = "InProgress" operationCanceled string = "Canceled" operationFailed string = "Failed" @@ -225,7 +220,7 @@ func updatePollingState(resp *http.Response, ps *pollingState) error { // 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 { + if m == http.MethodPatch || m == http.MethodPut || m == http.MethodGet { ps.uri = req.URL.String() } } diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/config.go b/vendor/github.com/Azure/go-autorest/autorest/azure/config.go deleted file mode 100644 index bea30b0d67ea..000000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/config.go +++ /dev/null @@ -1,13 +0,0 @@ -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/environments.go b/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go index 3af1b48d270d..1cf55651f2a4 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go @@ -2,14 +2,9 @@ package azure import ( "fmt" - "net/url" "strings" ) -const ( - activeDirectoryAPIVersion = "1.0" -) - var environments = map[string]Environment{ "AZURECHINACLOUD": ChinaCloud, "AZUREGERMANCLOUD": GermanCloud, @@ -35,6 +30,7 @@ type Environment struct { ServiceBusEndpointSuffix string `json:"serviceBusEndpointSuffix"` ServiceManagementVMDNSSuffix string `json:"serviceManagementVMDNSSuffix"` ResourceManagerVMDNSSuffix string `json:"resourceManagerVMDNSSuffix"` + ContainerRegistryDNSSuffix string `json:"containerRegistryDNSSuffix"` } var ( @@ -56,6 +52,7 @@ var ( ServiceBusEndpointSuffix: "servicebus.azure.com", ServiceManagementVMDNSSuffix: "cloudapp.net", ResourceManagerVMDNSSuffix: "cloudapp.azure.com", + ContainerRegistryDNSSuffix: "azurecr.io", } // USGovernmentCloud is the cloud environment for the US Government @@ -76,6 +73,7 @@ var ( ServiceBusEndpointSuffix: "servicebus.usgovcloudapi.net", ServiceManagementVMDNSSuffix: "usgovcloudapp.net", ResourceManagerVMDNSSuffix: "cloudapp.windowsazure.us", + ContainerRegistryDNSSuffix: "azurecr.io", } // ChinaCloud is the cloud environment operated in China @@ -85,7 +83,7 @@ var ( 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", + ActiveDirectoryEndpoint: "https://login.chinacloudapi.cn/", GalleryEndpoint: "https://gallery.chinacloudapi.cn/", KeyVaultEndpoint: "https://vault.azure.cn/", GraphEndpoint: "https://graph.chinacloudapi.cn/", @@ -96,6 +94,7 @@ var ( ServiceBusEndpointSuffix: "servicebus.chinacloudapi.net", ServiceManagementVMDNSSuffix: "chinacloudapp.cn", ResourceManagerVMDNSSuffix: "cloudapp.azure.cn", + ContainerRegistryDNSSuffix: "azurecr.io", } // GermanCloud is the cloud environment operated in Germany @@ -116,6 +115,7 @@ var ( ServiceBusEndpointSuffix: "servicebus.cloudapi.de", ServiceManagementVMDNSSuffix: "azurecloudapp.de", ResourceManagerVMDNSSuffix: "cloudapp.microsoftazure.de", + ContainerRegistryDNSSuffix: "azurecr.io", } ) @@ -128,35 +128,3 @@ func EnvironmentFromName(name string) (Environment, error) { } return env, nil } - -// OAuthConfigForTenant returns an OAuthConfig with tenant specific urls -func (env Environment) OAuthConfigForTenant(tenantID string) (*OAuthConfig, error) { - return OAuthConfigForTenant(env.ActiveDirectoryEndpoint, tenantID) -} - -// OAuthConfigForTenant returns an OAuthConfig with tenant specific urls for target cloud auth endpoint -func OAuthConfigForTenant(activeDirectoryEndpoint, tenantID string) (*OAuthConfig, error) { - template := "%s/oauth2/%s?api-version=%s" - u, err := url.Parse(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/client.go b/vendor/github.com/Azure/go-autorest/autorest/client.go index b55b3d103534..b5f94b5c3c75 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/client.go +++ b/vendor/github.com/Azure/go-autorest/autorest/client.go @@ -8,6 +8,7 @@ import ( "log" "net/http" "net/http/cookiejar" + "runtime" "time" ) @@ -22,13 +23,24 @@ const ( DefaultRetryAttempts = 3 ) -var statusCodesForRetry = []int{ - http.StatusRequestTimeout, // 408 - http.StatusInternalServerError, // 500 - http.StatusBadGateway, // 502 - http.StatusServiceUnavailable, // 503 - http.StatusGatewayTimeout, // 504 -} +var ( + // defaultUserAgent builds a string containing the Go version, system archityecture and OS, + // and the go-autorest version. + defaultUserAgent = fmt.Sprintf("Go/%s (%s-%s) go-autorest/%s", + runtime.Version(), + runtime.GOARCH, + runtime.GOOS, + Version(), + ) + + statusCodesForRetry = []int{ + http.StatusRequestTimeout, // 408 + http.StatusInternalServerError, // 500 + http.StatusBadGateway, // 502 + http.StatusServiceUnavailable, // 503 + http.StatusGatewayTimeout, // 504 + } +) const ( requestFormat = `HTTP Request Begin =================================================== @@ -140,13 +152,24 @@ type Client struct { // NewClientWithUserAgent returns an instance of a Client with the UserAgent set to the passed // string. func NewClientWithUserAgent(ua string) Client { - return Client{ + c := Client{ PollingDelay: DefaultPollingDelay, PollingDuration: DefaultPollingDuration, RetryAttempts: DefaultRetryAttempts, RetryDuration: 30 * time.Second, - UserAgent: ua, + UserAgent: defaultUserAgent, + } + c.AddToUserAgent(ua) + return c +} + +// AddToUserAgent adds an extension to the current user agent +func (c *Client) AddToUserAgent(extension string) error { + if extension != "" { + c.UserAgent = fmt.Sprintf("%s %s", c.UserAgent, extension) + return nil } + return fmt.Errorf("Extension was empty, User Agent stayed as %s", c.UserAgent) } // Do implements the Sender interface by invoking the active Sender after applying authorization. diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/BUILD b/vendor/github.com/Azure/go-autorest/autorest/date/BUILD index 09dea654292f..c1123df662cc 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/date/BUILD +++ b/vendor/github.com/Azure/go-autorest/autorest/date/BUILD @@ -13,6 +13,7 @@ go_library( "date.go", "time.go", "timerfc1123.go", + "unixtime.go", "utility.go", ], tags = ["automanaged"], diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/unixtime.go b/vendor/github.com/Azure/go-autorest/autorest/date/unixtime.go new file mode 100644 index 000000000000..e085c77eea50 --- /dev/null +++ b/vendor/github.com/Azure/go-autorest/autorest/date/unixtime.go @@ -0,0 +1,109 @@ +package date + +import ( + "bytes" + "encoding/binary" + "encoding/json" + "time" +) + +// unixEpoch is the moment in time that should be treated as timestamp 0. +var unixEpoch = time.Date(1970, time.January, 1, 0, 0, 0, 0, time.UTC) + +// UnixTime marshals and unmarshals a time that is represented as the number +// of seconds (ignoring skip-seconds) since the Unix Epoch. +type UnixTime time.Time + +// Duration returns the time as a Duration since the UnixEpoch. +func (t UnixTime) Duration() time.Duration { + return time.Time(t).Sub(unixEpoch) +} + +// NewUnixTimeFromSeconds creates a UnixTime as a number of seconds from the UnixEpoch. +func NewUnixTimeFromSeconds(seconds float64) UnixTime { + return NewUnixTimeFromDuration(time.Duration(seconds * float64(time.Second))) +} + +// NewUnixTimeFromNanoseconds creates a UnixTime as a number of nanoseconds from the UnixEpoch. +func NewUnixTimeFromNanoseconds(nanoseconds int64) UnixTime { + return NewUnixTimeFromDuration(time.Duration(nanoseconds)) +} + +// NewUnixTimeFromDuration creates a UnixTime as a duration of time since the UnixEpoch. +func NewUnixTimeFromDuration(dur time.Duration) UnixTime { + return UnixTime(unixEpoch.Add(dur)) +} + +// UnixEpoch retreives the moment considered the Unix Epoch. I.e. The time represented by '0' +func UnixEpoch() time.Time { + return unixEpoch +} + +// MarshalJSON preserves the UnixTime as a JSON number conforming to Unix Timestamp requirements. +// (i.e. the number of seconds since midnight January 1st, 1970 not considering leap seconds.) +func (t UnixTime) MarshalJSON() ([]byte, error) { + buffer := &bytes.Buffer{} + enc := json.NewEncoder(buffer) + err := enc.Encode(float64(time.Time(t).UnixNano()) / 1e9) + if err != nil { + return nil, err + } + return buffer.Bytes(), nil +} + +// UnmarshalJSON reconstitures a UnixTime saved as a JSON number of the number of seconds since +// midnight January 1st, 1970. +func (t *UnixTime) UnmarshalJSON(text []byte) error { + dec := json.NewDecoder(bytes.NewReader(text)) + + var secondsSinceEpoch float64 + if err := dec.Decode(&secondsSinceEpoch); err != nil { + return err + } + + *t = NewUnixTimeFromSeconds(secondsSinceEpoch) + + return nil +} + +// MarshalText stores the number of seconds since the Unix Epoch as a textual floating point number. +func (t UnixTime) MarshalText() ([]byte, error) { + cast := time.Time(t) + return cast.MarshalText() +} + +// UnmarshalText populates a UnixTime with a value stored textually as a floating point number of seconds since the Unix Epoch. +func (t *UnixTime) UnmarshalText(raw []byte) error { + var unmarshaled time.Time + + if err := unmarshaled.UnmarshalText(raw); err != nil { + return err + } + + *t = UnixTime(unmarshaled) + return nil +} + +// MarshalBinary converts a UnixTime into a binary.LittleEndian float64 of nanoseconds since the epoch. +func (t UnixTime) MarshalBinary() ([]byte, error) { + buf := &bytes.Buffer{} + + payload := int64(t.Duration()) + + if err := binary.Write(buf, binary.LittleEndian, &payload); err != nil { + return nil, err + } + + return buf.Bytes(), nil +} + +// UnmarshalBinary converts a from a binary.LittleEndian float64 of nanoseconds since the epoch into a UnixTime. +func (t *UnixTime) UnmarshalBinary(raw []byte) error { + var nanosecondsSinceEpoch int64 + + if err := binary.Read(bytes.NewReader(raw), binary.LittleEndian, &nanosecondsSinceEpoch); err != nil { + return err + } + *t = NewUnixTimeFromNanoseconds(nanosecondsSinceEpoch) + return nil +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/preparer.go b/vendor/github.com/Azure/go-autorest/autorest/preparer.go index 5b2c52704a29..afd114821bc7 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/preparer.go +++ b/vendor/github.com/Azure/go-autorest/autorest/preparer.go @@ -183,6 +183,16 @@ func WithBaseURL(baseURL string) PrepareDecorator { } } +// WithCustomBaseURL returns a PrepareDecorator that replaces brace-enclosed keys within the +// request base URL (i.e., http.Request.URL) with the corresponding values from the passed map. +func WithCustomBaseURL(baseURL string, urlParameters map[string]interface{}) PrepareDecorator { + parameters := ensureValueStrings(urlParameters) + for key, value := range parameters { + baseURL = strings.Replace(baseURL, "{"+key+"}", value, -1) + } + return WithBaseURL(baseURL) +} + // WithFormData returns a PrepareDecoratore that "URL encodes" (e.g., bar=baz&foo=quux) into the // http.Request body. func WithFormData(v url.Values) PrepareDecorator { @@ -416,18 +426,3 @@ func WithQueryParameters(queryParameters map[string]interface{}) PrepareDecorato }) } } - -// Authorizer is the interface that provides a PrepareDecorator used to supply request -// authorization. Most often, the Authorizer decorator runs last so it has access to the full -// state of the formed HTTP request. -type Authorizer interface { - WithAuthorization() PrepareDecorator -} - -// NullAuthorizer implements a default, "do nothing" Authorizer. -type NullAuthorizer struct{} - -// WithAuthorization returns a PrepareDecorator that does nothing. -func (na NullAuthorizer) WithAuthorization() PrepareDecorator { - return WithNothing() -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/responder.go b/vendor/github.com/Azure/go-autorest/autorest/responder.go index 07cd7ef5cc8c..87f71e5854b5 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/responder.go +++ b/vendor/github.com/Azure/go-autorest/autorest/responder.go @@ -5,6 +5,7 @@ import ( "encoding/json" "encoding/xml" "fmt" + "io" "io/ioutil" "net/http" "strings" @@ -87,6 +88,24 @@ func ByCopying(b *bytes.Buffer) RespondDecorator { } } +// ByDiscardingBody returns a RespondDecorator that first invokes the passed Responder after which +// it copies the remaining bytes (if any) in the response body to ioutil.Discard. Since the passed +// Responder is invoked prior to discarding the response body, the decorator may occur anywhere +// within the set. +func ByDiscardingBody() 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 { + if _, err := io.Copy(ioutil.Discard, resp.Body); err != nil { + return fmt.Errorf("Error discarding the response body: %v", err) + } + } + 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. @@ -128,6 +147,8 @@ func ByUnmarshallingJSON(v interface{}) RespondDecorator { err := r.Respond(resp) if err == nil { b, errInner := ioutil.ReadAll(resp.Body) + // Some responses might include a BOM, remove for successful unmarshalling + b = bytes.TrimPrefix(b, []byte("\xef\xbb\xbf")) if errInner != nil { err = fmt.Errorf("Error occurred reading http.Response#Body - Error = '%v'", errInner) } else if len(strings.Trim(string(b), " ")) > 0 { diff --git a/vendor/github.com/Azure/go-autorest/autorest/sender.go b/vendor/github.com/Azure/go-autorest/autorest/sender.go index a12f0f7ff551..9c0697815bba 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/sender.go +++ b/vendor/github.com/Azure/go-autorest/autorest/sender.go @@ -97,7 +97,7 @@ func DoCloseIfError() SendDecorator { return SenderFunc(func(r *http.Request) (*http.Response, error) { resp, err := s.Do(r) if err != nil { - Respond(resp, ByClosing()) + Respond(resp, ByDiscardingBody(), ByClosing()) } return resp, err }) @@ -156,6 +156,7 @@ func DoPollForStatusCodes(duration time.Duration, delay time.Duration, codes ... for err == nil && ResponseHasStatusCode(resp, codes...) { Respond(resp, + ByDiscardingBody(), ByClosing()) resp, err = SendWithSender(s, r, AfterDelay(GetRetryAfter(resp, delay))) diff --git a/vendor/github.com/Azure/go-autorest/autorest/version.go b/vendor/github.com/Azure/go-autorest/autorest/version.go index 8031a332cd2d..a222e8efaaf9 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/version.go +++ b/vendor/github.com/Azure/go-autorest/autorest/version.go @@ -1,18 +1,35 @@ package autorest import ( + "bytes" "fmt" + "strings" + "sync" ) const ( - major = "7" - minor = "0" - patch = "0" - tag = "" - semVerFormat = "%s.%s.%s%s" + major = 8 + minor = 0 + patch = 0 + tag = "" ) +var once sync.Once +var version string + // Version returns the semantic version (see http://semver.org). func Version() string { - return fmt.Sprintf(semVerFormat, major, minor, patch, tag) + once.Do(func() { + semver := fmt.Sprintf("%d.%d.%d", major, minor, patch) + verBuilder := bytes.NewBufferString(semver) + if tag != "" && tag != "-" { + updated := strings.TrimPrefix(tag, "-") + _, err := verBuilder.WriteString("-" + updated) + if err == nil { + verBuilder = bytes.NewBufferString(semver) + } + } + version = verBuilder.String() + }) + return version } diff --git a/vendor/github.com/satori/uuid/.travis.yml b/vendor/github.com/satori/uuid/.travis.yml new file mode 100644 index 000000000000..fdf960e86b55 --- /dev/null +++ b/vendor/github.com/satori/uuid/.travis.yml @@ -0,0 +1,22 @@ +language: go +sudo: false +go: + - 1.2 + - 1.3 + - 1.4 + - 1.5 + - 1.6 + - 1.7 + - 1.8 + - tip +matrix: + allow_failures: + - go: tip + fast_finish: true +before_install: + - go get github.com/mattn/goveralls + - go get golang.org/x/tools/cmd/cover +script: + - $HOME/gopath/bin/goveralls -service=travis-ci +notifications: + email: false diff --git a/vendor/github.com/satori/uuid/BUILD b/vendor/github.com/satori/uuid/BUILD new file mode 100644 index 000000000000..0ab5752bdbbf --- /dev/null +++ b/vendor/github.com/satori/uuid/BUILD @@ -0,0 +1,27 @@ +package(default_visibility = ["//visibility:public"]) + +licenses(["notice"]) + +load( + "@io_bazel_rules_go//go:def.bzl", + "go_library", +) + +go_library( + name = "go_default_library", + srcs = ["uuid.go"], + tags = ["automanaged"], +) + +filegroup( + name = "package-srcs", + srcs = glob(["**"]), + tags = ["automanaged"], + visibility = ["//visibility:private"], +) + +filegroup( + name = "all-srcs", + srcs = [":package-srcs"], + tags = ["automanaged"], +) diff --git a/vendor/github.com/satori/uuid/LICENSE b/vendor/github.com/satori/uuid/LICENSE new file mode 100644 index 000000000000..488357b8af1f --- /dev/null +++ b/vendor/github.com/satori/uuid/LICENSE @@ -0,0 +1,20 @@ +Copyright (C) 2013-2016 by Maxim Bublis + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/satori/uuid/README.md b/vendor/github.com/satori/uuid/README.md new file mode 100644 index 000000000000..b6aad1c81303 --- /dev/null +++ b/vendor/github.com/satori/uuid/README.md @@ -0,0 +1,65 @@ +# UUID package for Go language + +[![Build Status](https://travis-ci.org/satori/go.uuid.png?branch=master)](https://travis-ci.org/satori/go.uuid) +[![Coverage Status](https://coveralls.io/repos/github/satori/go.uuid/badge.svg?branch=master)](https://coveralls.io/github/satori/go.uuid) +[![GoDoc](http://godoc.org/github.com/satori/go.uuid?status.png)](http://godoc.org/github.com/satori/go.uuid) + +This package provides pure Go implementation of Universally Unique Identifier (UUID). Supported both creation and parsing of UUIDs. + +With 100% test coverage and benchmarks out of box. + +Supported versions: +* Version 1, based on timestamp and MAC address (RFC 4122) +* Version 2, based on timestamp, MAC address and POSIX UID/GID (DCE 1.1) +* Version 3, based on MD5 hashing (RFC 4122) +* Version 4, based on random numbers (RFC 4122) +* Version 5, based on SHA-1 hashing (RFC 4122) + +## Installation + +Use the `go` command: + + $ go get github.com/satori/go.uuid + +## Requirements + +UUID package requires Go >= 1.2. + +## Example + +```go +package main + +import ( + "fmt" + "github.com/satori/go.uuid" +) + +func main() { + // Creating UUID Version 4 + u1 := uuid.NewV4() + fmt.Printf("UUIDv4: %s\n", u1) + + // Parsing UUID from string input + u2, err := uuid.FromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8") + if err != nil { + fmt.Printf("Something gone wrong: %s", err) + } + fmt.Printf("Successfully parsed: %s", u2) +} +``` + +## Documentation + +[Documentation](http://godoc.org/github.com/satori/go.uuid) is hosted at GoDoc project. + +## Links +* [RFC 4122](http://tools.ietf.org/html/rfc4122) +* [DCE 1.1: Authentication and Security Services](http://pubs.opengroup.org/onlinepubs/9696989899/chap5.htm#tagcjh_08_02_01_01) + +## Copyright + +Copyright (C) 2013-2016 by Maxim Bublis . + +UUID package released under MIT License. +See [LICENSE](https://github.com/satori/go.uuid/blob/master/LICENSE) for details. diff --git a/vendor/github.com/satori/uuid/uuid.go b/vendor/github.com/satori/uuid/uuid.go new file mode 100644 index 000000000000..295f3fc2c57f --- /dev/null +++ b/vendor/github.com/satori/uuid/uuid.go @@ -0,0 +1,481 @@ +// Copyright (C) 2013-2015 by Maxim Bublis +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +// Package uuid provides implementation of Universally Unique Identifier (UUID). +// Supported versions are 1, 3, 4 and 5 (as specified in RFC 4122) and +// version 2 (as specified in DCE 1.1). +package uuid + +import ( + "bytes" + "crypto/md5" + "crypto/rand" + "crypto/sha1" + "database/sql/driver" + "encoding/binary" + "encoding/hex" + "fmt" + "hash" + "net" + "os" + "sync" + "time" +) + +// UUID layout variants. +const ( + VariantNCS = iota + VariantRFC4122 + VariantMicrosoft + VariantFuture +) + +// UUID DCE domains. +const ( + DomainPerson = iota + DomainGroup + DomainOrg +) + +// Difference in 100-nanosecond intervals between +// UUID epoch (October 15, 1582) and Unix epoch (January 1, 1970). +const epochStart = 122192928000000000 + +// Used in string method conversion +const dash byte = '-' + +// UUID v1/v2 storage. +var ( + storageMutex sync.Mutex + storageOnce sync.Once + epochFunc = unixTimeFunc + clockSequence uint16 + lastTime uint64 + hardwareAddr [6]byte + posixUID = uint32(os.Getuid()) + posixGID = uint32(os.Getgid()) +) + +// String parse helpers. +var ( + urnPrefix = []byte("urn:uuid:") + byteGroups = []int{8, 4, 4, 4, 12} +) + +func initClockSequence() { + buf := make([]byte, 2) + safeRandom(buf) + clockSequence = binary.BigEndian.Uint16(buf) +} + +func initHardwareAddr() { + interfaces, err := net.Interfaces() + if err == nil { + for _, iface := range interfaces { + if len(iface.HardwareAddr) >= 6 { + copy(hardwareAddr[:], iface.HardwareAddr) + return + } + } + } + + // Initialize hardwareAddr randomly in case + // of real network interfaces absence + safeRandom(hardwareAddr[:]) + + // Set multicast bit as recommended in RFC 4122 + hardwareAddr[0] |= 0x01 +} + +func initStorage() { + initClockSequence() + initHardwareAddr() +} + +func safeRandom(dest []byte) { + if _, err := rand.Read(dest); err != nil { + panic(err) + } +} + +// Returns difference in 100-nanosecond intervals between +// UUID epoch (October 15, 1582) and current time. +// This is default epoch calculation function. +func unixTimeFunc() uint64 { + return epochStart + uint64(time.Now().UnixNano()/100) +} + +// UUID representation compliant with specification +// described in RFC 4122. +type UUID [16]byte + +// NullUUID can be used with the standard sql package to represent a +// UUID value that can be NULL in the database +type NullUUID struct { + UUID UUID + Valid bool +} + +// The nil UUID is special form of UUID that is specified to have all +// 128 bits set to zero. +var Nil = UUID{} + +// Predefined namespace UUIDs. +var ( + NamespaceDNS, _ = FromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8") + NamespaceURL, _ = FromString("6ba7b811-9dad-11d1-80b4-00c04fd430c8") + NamespaceOID, _ = FromString("6ba7b812-9dad-11d1-80b4-00c04fd430c8") + NamespaceX500, _ = FromString("6ba7b814-9dad-11d1-80b4-00c04fd430c8") +) + +// And returns result of binary AND of two UUIDs. +func And(u1 UUID, u2 UUID) UUID { + u := UUID{} + for i := 0; i < 16; i++ { + u[i] = u1[i] & u2[i] + } + return u +} + +// Or returns result of binary OR of two UUIDs. +func Or(u1 UUID, u2 UUID) UUID { + u := UUID{} + for i := 0; i < 16; i++ { + u[i] = u1[i] | u2[i] + } + return u +} + +// Equal returns true if u1 and u2 equals, otherwise returns false. +func Equal(u1 UUID, u2 UUID) bool { + return bytes.Equal(u1[:], u2[:]) +} + +// Version returns algorithm version used to generate UUID. +func (u UUID) Version() uint { + return uint(u[6] >> 4) +} + +// Variant returns UUID layout variant. +func (u UUID) Variant() uint { + switch { + case (u[8] & 0x80) == 0x00: + return VariantNCS + case (u[8]&0xc0)|0x80 == 0x80: + return VariantRFC4122 + case (u[8]&0xe0)|0xc0 == 0xc0: + return VariantMicrosoft + } + return VariantFuture +} + +// Bytes returns bytes slice representation of UUID. +func (u UUID) Bytes() []byte { + return u[:] +} + +// Returns canonical string representation of UUID: +// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx. +func (u UUID) String() string { + buf := make([]byte, 36) + + hex.Encode(buf[0:8], u[0:4]) + buf[8] = dash + hex.Encode(buf[9:13], u[4:6]) + buf[13] = dash + hex.Encode(buf[14:18], u[6:8]) + buf[18] = dash + hex.Encode(buf[19:23], u[8:10]) + buf[23] = dash + hex.Encode(buf[24:], u[10:]) + + return string(buf) +} + +// SetVersion sets version bits. +func (u *UUID) SetVersion(v byte) { + u[6] = (u[6] & 0x0f) | (v << 4) +} + +// SetVariant sets variant bits as described in RFC 4122. +func (u *UUID) SetVariant() { + u[8] = (u[8] & 0xbf) | 0x80 +} + +// MarshalText implements the encoding.TextMarshaler interface. +// The encoding is the same as returned by String. +func (u UUID) MarshalText() (text []byte, err error) { + text = []byte(u.String()) + return +} + +// UnmarshalText implements the encoding.TextUnmarshaler interface. +// Following formats are supported: +// "6ba7b810-9dad-11d1-80b4-00c04fd430c8", +// "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}", +// "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8" +func (u *UUID) UnmarshalText(text []byte) (err error) { + if len(text) < 32 { + err = fmt.Errorf("uuid: UUID string too short: %s", text) + return + } + + t := text[:] + braced := false + + if bytes.Equal(t[:9], urnPrefix) { + t = t[9:] + } else if t[0] == '{' { + braced = true + t = t[1:] + } + + b := u[:] + + for i, byteGroup := range byteGroups { + if i > 0 { + if t[0] != '-' { + err = fmt.Errorf("uuid: invalid string format") + return + } + t = t[1:] + } + + if len(t) < byteGroup { + err = fmt.Errorf("uuid: UUID string too short: %s", text) + return + } + + if i == 4 && len(t) > byteGroup && + ((braced && t[byteGroup] != '}') || len(t[byteGroup:]) > 1 || !braced) { + err = fmt.Errorf("uuid: UUID string too long: %s", text) + return + } + + _, err = hex.Decode(b[:byteGroup/2], t[:byteGroup]) + if err != nil { + return + } + + t = t[byteGroup:] + b = b[byteGroup/2:] + } + + return +} + +// MarshalBinary implements the encoding.BinaryMarshaler interface. +func (u UUID) MarshalBinary() (data []byte, err error) { + data = u.Bytes() + return +} + +// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. +// It will return error if the slice isn't 16 bytes long. +func (u *UUID) UnmarshalBinary(data []byte) (err error) { + if len(data) != 16 { + err = fmt.Errorf("uuid: UUID must be exactly 16 bytes long, got %d bytes", len(data)) + return + } + copy(u[:], data) + + return +} + +// Value implements the driver.Valuer interface. +func (u UUID) Value() (driver.Value, error) { + return u.String(), nil +} + +// Scan implements the sql.Scanner interface. +// A 16-byte slice is handled by UnmarshalBinary, while +// a longer byte slice or a string is handled by UnmarshalText. +func (u *UUID) Scan(src interface{}) error { + switch src := src.(type) { + case []byte: + if len(src) == 16 { + return u.UnmarshalBinary(src) + } + return u.UnmarshalText(src) + + case string: + return u.UnmarshalText([]byte(src)) + } + + return fmt.Errorf("uuid: cannot convert %T to UUID", src) +} + +// Value implements the driver.Valuer interface. +func (u NullUUID) Value() (driver.Value, error) { + if !u.Valid { + return nil, nil + } + // Delegate to UUID Value function + return u.UUID.Value() +} + +// Scan implements the sql.Scanner interface. +func (u *NullUUID) Scan(src interface{}) error { + if src == nil { + u.UUID, u.Valid = Nil, false + return nil + } + + // Delegate to UUID Scan function + u.Valid = true + return u.UUID.Scan(src) +} + +// FromBytes returns UUID converted from raw byte slice input. +// It will return error if the slice isn't 16 bytes long. +func FromBytes(input []byte) (u UUID, err error) { + err = u.UnmarshalBinary(input) + return +} + +// FromBytesOrNil returns UUID converted from raw byte slice input. +// Same behavior as FromBytes, but returns a Nil UUID on error. +func FromBytesOrNil(input []byte) UUID { + uuid, err := FromBytes(input) + if err != nil { + return Nil + } + return uuid +} + +// FromString returns UUID parsed from string input. +// Input is expected in a form accepted by UnmarshalText. +func FromString(input string) (u UUID, err error) { + err = u.UnmarshalText([]byte(input)) + return +} + +// FromStringOrNil returns UUID parsed from string input. +// Same behavior as FromString, but returns a Nil UUID on error. +func FromStringOrNil(input string) UUID { + uuid, err := FromString(input) + if err != nil { + return Nil + } + return uuid +} + +// Returns UUID v1/v2 storage state. +// Returns epoch timestamp, clock sequence, and hardware address. +func getStorage() (uint64, uint16, []byte) { + storageOnce.Do(initStorage) + + storageMutex.Lock() + defer storageMutex.Unlock() + + timeNow := epochFunc() + // Clock changed backwards since last UUID generation. + // Should increase clock sequence. + if timeNow <= lastTime { + clockSequence++ + } + lastTime = timeNow + + return timeNow, clockSequence, hardwareAddr[:] +} + +// NewV1 returns UUID based on current timestamp and MAC address. +func NewV1() UUID { + u := UUID{} + + timeNow, clockSeq, hardwareAddr := getStorage() + + binary.BigEndian.PutUint32(u[0:], uint32(timeNow)) + binary.BigEndian.PutUint16(u[4:], uint16(timeNow>>32)) + binary.BigEndian.PutUint16(u[6:], uint16(timeNow>>48)) + binary.BigEndian.PutUint16(u[8:], clockSeq) + + copy(u[10:], hardwareAddr) + + u.SetVersion(1) + u.SetVariant() + + return u +} + +// NewV2 returns DCE Security UUID based on POSIX UID/GID. +func NewV2(domain byte) UUID { + u := UUID{} + + timeNow, clockSeq, hardwareAddr := getStorage() + + switch domain { + case DomainPerson: + binary.BigEndian.PutUint32(u[0:], posixUID) + case DomainGroup: + binary.BigEndian.PutUint32(u[0:], posixGID) + } + + binary.BigEndian.PutUint16(u[4:], uint16(timeNow>>32)) + binary.BigEndian.PutUint16(u[6:], uint16(timeNow>>48)) + binary.BigEndian.PutUint16(u[8:], clockSeq) + u[9] = domain + + copy(u[10:], hardwareAddr) + + u.SetVersion(2) + u.SetVariant() + + return u +} + +// NewV3 returns UUID based on MD5 hash of namespace UUID and name. +func NewV3(ns UUID, name string) UUID { + u := newFromHash(md5.New(), ns, name) + u.SetVersion(3) + u.SetVariant() + + return u +} + +// NewV4 returns random generated UUID. +func NewV4() UUID { + u := UUID{} + safeRandom(u[:]) + u.SetVersion(4) + u.SetVariant() + + return u +} + +// NewV5 returns UUID based on SHA-1 hash of namespace UUID and name. +func NewV5(ns UUID, name string) UUID { + u := newFromHash(sha1.New(), ns, name) + u.SetVersion(5) + u.SetVariant() + + return u +} + +// Returns UUID based on hashing of namespace UUID and name. +func newFromHash(h hash.Hash, ns UUID, name string) UUID { + u := UUID{} + h.Write(ns[:]) + h.Write([]byte(name)) + copy(u[:], h.Sum(nil)) + + return u +}